One solution to achieve this is to create a global observer class that listens to all Eloquent model events and DB queries. Here's an example implementation:
<?php
namespace App\Observers;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
class GlobalObserver
{
public function created($model)
{
// handle created event
}
public function updated($model)
{
// handle updated event
}
public function deleted($model)
{
// handle deleted event
}
public function retrieved($model)
{
// handle retrieved event
}
public function queryExecuted(QueryExecuted $query)
{
// handle query executed event
}
public function register()
{
foreach ($this->getModels() as $model) {
$model::observe($this);
}
DB::listen(function (QueryExecuted $query) {
$this->queryExecuted($query);
});
}
protected function getModels()
{
// return an array of all Eloquent models you want to observe
return [
\App\Models\User::class,
\App\Models\Post::class,
// add more models here
];
}
}
In this example, the GlobalObserver class defines methods for handling all Eloquent model events (created, updated, deleted, and retrieved) as well as a method for handling DB query executed events (queryExecuted). The register method is called to register the observer with all the Eloquent models and the DB query listener.
To use this observer, you can simply call the register method in your AppServiceProvider:
<?php
namespace App\Providers;
use App\Observers\GlobalObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
GlobalObserver::register();
}
}
This will register the GlobalObserver with all the Eloquent models and the DB query listener, allowing you to capture all events in a single class.