In Laravel 4 can do:
$queries = DB::getQueryLog(); // array de todas as queries que foram corridas
Already on 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 activate the log for one of them (one of the connections):
DB::connection('connection')->enableQueryLog();
Where to place this activation?
This can be put in 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 recover 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 Artisan (CLI) comes into action this is set right away:
$app['events']->listen('artisan.start', function(){
\DB::enableQueryLog();
});
In case 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
Try putting
...->toSql()
instead of...->get()
. Is that?– Miguel
But this will not make the query. This will convert the query to
Model
in an SQL string. I want to continue running theGet()
and discover all queries that were executed on the pages.– Wallace Maxters
I’ve never done that, and I don’t want to risk responding without testing. See if this helps? http://stackoverflow.com/questions/27753868/how-to-get-the-query-executed-in-laravel-5-dbgetquerylog-returning-empty-arr , http://stackoverflow.com/questions/14536165/get-the-query-executed-in-laravel-3-4
– Miguel
It works, Miguel. I asked this question to give an opportunity for someone to answer it. I already knew the answer. You should run
DB::enableQueryLog
before the queries. Hence, from the query you want to capture thelog
, you call him before. Then at the end of all queries Voce callsgetQueryLog
to capture them.– Wallace Maxters
You may answer, young man!
– Wallace Maxters