I'm trying to sync my database with an external service.
I'm using Algolia search in a couple of places across a web application.
It's indexed with a couple of models however I need it to re-index in the event that any changes are made to the database i.e. when multiple model events are fired.
My first approach was to action everything within the boot method of the AppServiceProvider
public function boot()
{
$events = ['created', 'updated', 'deleted', 'restored'];
// reindex handlers for models relevant to Algolia search
foreach ($events as $evt) {
Order::registerModelEvent($evt, function () {
Order::reindex();
});
Product::registerModelEvent($evt, function () {
Product::reindex();
Product::setSettings();
});
}
}
This is my approach to avoid multiple conditionals using the standard model functions exampled in the docs.
However I'm assuming there's a better way using Laravel Event Listeners.
namespace App\Listeners;
class OrderEventListener
{
// handlers
public function subscribe($events)
{
$events->listen(
// model events
);
}
}
Although I'm unsure how to tap into the model events in the listen method.
ProductCreatedEvent
is fired. I'm ok with this because I need only trigger it withself::updated()
in the boot method like you show. However something like re-indexing here should be executed whenever any model event is fired and I was looking for a solution that didn't require listing every model event with subsequent event listeners, handlers etc. Looking into it more would it not be better to create a job and dispatch it in boot? Then it can still implement ShouldQueue but it will always fire. – Acre