ahcanor
1/2/2017 - 9:10 PM

Query Debug

Query Debug


\DB::listen(function($sql, $bindings, $time) {
	dump($sql);
	dump($bindings);
	dump($time);
});


By default query log disabled in Laravel 5 https://github.com/laravel/framework/commit/e0abfe5c49d225567cb4dfd56df9ef05cc297448

You need enable query log by calling

DB::enableQueryLog();
or register event listener

DB::listen(
    function ($sql, $bindings, $time) {
        //  $sql - select * from `ncv_users` where `ncv_users`.`id` = ? limit 1
        //  $bindings - [5]
        //  $time(in milliseconds) - 0.38 
    }
);  
Some Tips

1. Multiple DB connections

If you have more than one DB connection you must specify it

Enables query log for my_connection

DB::connection('my_connection')->enableQueryLog();
Get query log for my_connection

print_r(
   DB::connection('my_connection')->getQueryLog()
);
2. Where to enable query log ?

For HTTP request lifecycle you can enable query log in  handle method of some BeforeAnyDbQueryMiddleware middleware and then retrieve the executed queries in terminate method of the same middleware.

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

    public function terminate($request, $response)
    {
        // Store or dump the log data...
        dd(
            DB::getQueryLog();
        );
    }
}
Middlewares chain will not run for artisan commands, so for CLI execution you can enable query log on artisan.start event listener.

For example you can put it in bootstrap/app.php file

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

Laravel keeps all queries in memory. So in some cases, such as when inserting a large number of rows or having long runing job with a lot of queries, this can cause the application to use excess memory.

In most cases you will need query log only for debuging, and if that is the case I will recomend you enable it only for development.

if (App::environment('local')) {
    // The environment is local
    DB::enableQueryLog();
}
References

https://laravel.com/docs/5.0/database#query-logging