Last Updated: February 25, 2016
·
2.347K
· jpcamara

Logging Queries in Laravel

Sometimes when you're debugging a query, you want to see what the raw SQL output would be to get a sense for what might be going wrong.

In Laravel, this is pretty simple to do.

\MyModel::where('id', 1)->first();
$queries = \DB::getQueryLog();

This provides a listing of all queries that have been run up until that point: the query itself, the bindings, and the time it took to run. In the case of our example, we'd end up with one query for the first model and the array returned would look like the following.

[
  'query' => '...',
  'bindings' => [...],
  'time' => 0.0
]

Laravel 5

This approach works in both Laravel 4 and Laravel 5. However, in Laravel 5 there is one more step you'll need to take: query logging is disabled by default, so let's enable it.

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

And there you go - now you can debug your query output with ease!