Navigation

Laravel

How to See All Executed Queries in Laravel

Debug and optimize your Laravel application by logging all database queries. Learn how to use DB::listen() to monitor SQL queries in real-time.

Problem: You need to debug database performance issues or see what SQL queries your Eloquent models are generating, but Laravel doesn't show queries by default.

Solution:

// Add to AppServiceProvider boot() method
use Illuminate\Support\Facades\DB;

public function boot()
{
    DB::listen(function ($query) {
        \Log::info($query->sql, [
            'bindings' => $query->bindings,
            'time' => $query->time
        ]);
    });
}

// Or dump queries directly during development
DB::listen(function ($query) {
    dump($query->sql);
    dump($query->bindings);
    dump($query->time . 'ms');
});

// For a specific code block only
DB::enableQueryLog();

// Your code here
$users = User::where('active', true)->get();

// Get the queries
$queries = DB::getQueryLog();
dd($queries);

Why it works: DB::listen() registers a callback that fires after each database query. You get the raw SQL, parameter bindings, and execution time. enableQueryLog() stores queries in memory for later retrieval - perfect for debugging specific code sections.

Tip: For production debugging, consider using Laravel Telescope or Debugbar packages for a more comprehensive solution.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel