What is query logging and debugging in Laravel?

Answer

Laravel provides several tools for inspecting and debugging queries. Log all queries: DB::enableQueryLog() then DB::getQueryLog() returns all executed queries with bindings and execution times. Listen to queries: DB::listen(fn($query) => Log::info($query->sql, ["bindings" => $query->bindings, "time" => $query->time])). Inspect the SQL of a query builder without executing: User::where("active", true)->toSql(). Get bindings: ->getBindings(). Combined: ->dd() dumps and dies, ->dump() outputs the SQL and continues. Count queries in a test: DB::countQueryLog() after enabling the log. Telescope automatically logs all queries with execution time and caller information. For long-running queries, enable MySQL's slow query log or set: DB::whenQueryingForLongerThan(500, fn() => alert()) to detect slow queries in real-time.