How to see the queries that were executed by eloquent in Laravel?

3

How can I find out which queries have been executed in Laravel?

For example, I have the following query:

$usuarios = Usuario::with('nivel')->where(['status' => 1])->get();

I would like to know which queries were executed. Can you log it on Laravel?

I would like to include Laravel 5 and 4 in the answers, as I usually use both.

    
asked by anonymous 24.08.2016 / 15:09

2 answers

2

In Laravel 4 you can do:

$queries = DB::getQueryLog(); // array de todas as queries que foram corridas

Already in Laravel 5, since the log is not active by default and we have to activate it:

use DB;
...
DB::enableQueryLog();
...
$queries = DB::getQueryLog(); // array de todas as queries que foram corridas

Still in Laravel 5, if you have multiple databases and only want to enable logging for one of them (one of the connections):

DB::connection('connection')->enableQueryLog();

Where to put this activation?

This can be put into a middleware that goes into action on some / some requests, so that everything that is done (queries in this case) in the rest of the request is saved, and finally we can use the method terminate to retrieve the stored queries:

class AntesDeQualquerQuery
{
    public function handle($request, Closure $next)
    {
        DB::enableQueryLog();
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // dump de todas as queries no termino de execução deste middleware
        dd(DB::getQueryLog());
    }
}

We can also put this in the file bootstrap/app.php , so each time the artisan (CLI) goes into action it is immediately set:

$app['events']->listen('artisan.start', function(){
    \DB::enableQueryLog();
});

If we need the logo only on site and not in production:

if (App::environment('local')) {
    // Se for local queremos ativar o log
    DB::enableQueryLog();
}

DOCUMENTATION

    
24.08.2016 / 15:46
1

Another way to see the queries executed by a request directly in the browser is through laravel-debugbar .

It is compatible with Laravel 4 and 5, and has a tab that shows all queries . It even has a setting that can also include the execution plan of that query.

    
24.08.2016 / 16:07