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