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.