data codes through eyeglasses

Log Laravel Eloquent SQL queries with parameter values

Frequently I find the need to see what SQL queries are actually generated magically by Eloquent. It really helps when I need to debug a query or figure out why its not performing well. Since I keep referring back to this very useful code snippet I thought its good to keep it here so its readily available for myself and anyone else. Add the following code in the boot() method of AppServiceProvider.php:

    public function boot() {
if (\App::environment('local')) {
DB::listen(
static fn($query) => logger(
Str::replaceArray('?', array_map(fn($binding) => '\'' . $binding . '\'', $query->bindings),
$query->sql
)
)
);
}
}

If you haven’t changed Laravel’s default logging configuration all queries executed will be logged in storage/logs/laravel.log. The full query including its parameter values will be included which makes it dead easy to then copy/paste and run EXPLAIN so you can see how you could optimize it. Note that this will only execute if APP_ENV is set to local so no sensitive information will be logged on your production logs.

Laravel 5.0 Final released

  • New project directory structure – now looks more intuitive.
  • Now more components implement interfaces for better extensibility.
  • Route Caching for faster performance.
  • Middleware support for routes.
  • Common Authentication functionality out of the box (controllers for authentication, registration, forgot password and their respective views are all included).
  • Job Scheduler so you only need to run one cron job and the scheduler picks what to run from the queued jobs for you.
  • and more…

Have a look at the release notes.