$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[December 27, 2025] Laravel

Laravel Database Query Log: Debugging

Laravel Database Query Log: Debugging

────────────────────────────────────────────────────────

Laravel Database Query Log: Debugging

Tip: Enable Query Log

DB::enableQueryLog();
// ... queries ...
dd(DB::getQueryLog());

Gotcha: Query Log Consumes Memory

In long-running processes, the query log grows unbounded. Call DB::flushQueryLog() periodically.

Tip: Listen to Individual Queries

DB::listen(function ($query) {
    Log::info($query->sql);
    Log::info($query->bindings);
    Log::info($query->time . 'ms');
});

Gotcha: Query Log in Production

Never enable query log in production. It stores every query in memory.

Tip: toSql() for Preview

echo User::where('active', true)->toSql();

Shows the SQL without executing.

Gotcha: explain() for Analysis

DB::select('EXPLAIN ' . User::where('active', true)->toSql());

Shows the query execution plan.

Tip: Use route:cache Carefully

php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.

Tip: Model APP_KEY Rotation

Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.

Gotcha: Local Scope Leaks

Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.

Senior Insight

Structured logging transformed how I debug production issues. Instead of Log::info('User registered'), I now use Log::info('User registered', ['user_id' => $user->id, 'source' => $request->header('Referer')]). The difference when grepping through a million-line log file is night and day. Also, set up log rotation from day one — I've seen a 50GB log file crash a server because nobody thought about rotation.

Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)

────────────────────────────────────────────────────────
<-- back to posts