Tobia
Tobia

Reputation: 9506

How to log all Eloquent queries

I'm using Eloquent standalone inside Slim3 framework. I would like to log all DB queries from Eloquent, I see some implementation but what I'm missing is to log the query when it is made and without an explicit code to insert after each model request.

I found this: Laravel Eloquent display query log It works, but the best I could get is a Slim middleware that at the end of all request logs at once al queries.

Probably I need a listener, but how can I use it and how get ALL queries? This is my eloquent bootup inside Slim:

$capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($config['db']);
    $capsule->getConnection("default")->enableQueryLog();
    $capsule->setAsGlobal();
    //$capsule->setEventDispatcher(new \Illuminate\Events\Dispatcher())->listen($events, $listener);
    $capsule->bootEloquent();

Upvotes: 1

Views: 1324

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Listen for query events on the connection:

$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($config['db']);
$capsule->getConnection("default")->enableQueryLog();
$capsule->setAsGlobal();

$capsule->getConnection()->setEventDispatcher(new \Illuminate\Events\Dispatcher);
$capsule->getConnection()->listen(function ($query) {
    // TODO: Log query.
});

$capsule->bootEloquent();

Upvotes: 3

Related Questions