Hey! In this article, I’ll show you how I get SQL query logs in Laravel 12 when I want to debug database issues or just see what queries are being run in the background.
Laravel gives you a few clean ways to track queries — using DB::listen()
, enabling query logs, or even saving them in a custom log file. Let’s check out how each one works.
Laravel 12 Get SQL Query Log
You can log queries directly using DB::listen()
.
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
public function boot()
{
DB::listen(function ($query) {
Log::info('SQL: ' . $query->sql);
Log::info('Bindings: ' . json_encode($query->bindings));
Log::info('Time: ' . $query->time . 'ms');
});
}
Now, every query will be logged in storage/logs/laravel.log
.
This is useful for logging queries temporarily during a request:
DB::enableQueryLog();
// Run your queries...
$queries = DB::getQueryLog();
dd($queries);
This dumps all queries that were executed in that request.
If you prefer a UI, install Laravel Debugbar:
composer require barryvdh/laravel-debugbar --dev
It automatically shows all queries on each page in a browser toolbar — no extra config needed.
This shows the raw SQL (with placeholders) before it's executed:
public function index()
{
$query = User::select("*")->toSql();
dd($query);
}
This returns something like:
"select * from `users`"
Note: It won’t show the actual bindings (values), just the SQL string.
This methods may be invoked on a query to dump the query's SQL with all parameter bindings properly substituted:
public function index()
{
$query = User::select("*")->ddRawSql();
dd($query);
}
This returns something like:
"select * from `users`"
The end() function can give the last executed query.
public function index()
{
DB::enableQueryLog();
$users = User::select("*")->get();
$query = DB::getQueryLog();
$query = end($query); // get the last executed query
dd($query);
}
If you want to only log slow queries (e.g. above 100ms), you can filter them:
DB::listen(function ($query) {
if ($query->time > 100) {
Log::warning('Slow query detected: ' . $query->sql);
}
});
This helps in performance tuning by focusing only on the expensive queries.
Personally, I use toSql()
when I’m writing queries, and enableQueryLog()
or Debugbar when I’m trying to catch real-time behavior.
Hope this helped! Save these snippets — you’ll use them often.
You might also like: