DEV Community

Cover image for How to Get the Last Executed Query in Laravel 13: Query Log, toRawSql and DB::listen
Muhammad Yasir Amin
Muhammad Yasir Amin

Posted on Originally published at yasiramin.dev

How to Get the Last Executed Query in Laravel 13: Query Log, toRawSql and DB::listen

To get the last executed query in Laravel 13, use DB::enableQueryLog() and then DB::getQueryLog(), or call toRawSql() on a query builder before running it. For every query in the app, register a DB::listen() callback.

Each option fits a different job, so this guide explains when to choose which and how to avoid logging queries in production by accident.

What do I need first?

  • Laravel 13 (current stable at the time of writing) and a supported PHP version.
  • A query you want to inspect, for example an Eloquent query with a few where clauses.

How do I see the SQL of a query without running it?

Call toSql() for the SQL with ? placeholders, or toRawSql() for the SQL with the bindings filled in.

use App\Models\Post;

$query = Post::where('status', 'published')
    ->where('views', '>', 100)
    ->orderByDesc('created_at');

echo $query->toSql();
// select * from "posts" where "status" = ? and "views" > ? order by "created_at" desc

echo $query->toRawSql();
// select * from "posts" where "status" = 'published' and "views" > 100 order by "created_at" desc
Enter fullscreen mode Exit fullscreen mode

Use toRawSql() only for debugging. It is meant for reading, not for running by hand with untrusted values.

How do I get the queries that actually ran?

Enable the query log for the connection, run your code, then read the log.

use Illuminate\Support\Facades\DB;

DB::enableQueryLog();

Post::where('status', 'published')->first();
User::find(1);

$queries = DB::getQueryLog();
$last = end($queries);

// $last['query']    SQL with placeholders
// $last['bindings'] bound values
// $last['time']     execution time in milliseconds
Enter fullscreen mode Exit fullscreen mode

The log lives in memory for the current request or process. In long-running workers, such as queue workers, it can grow without limit, so call DB::disableQueryLog() or DB::flushQueryLog() when you are done.

How do I log every query with DB::listen?

Register a listener in AppServiceProvider::boot(). The callback receives a QueryExecuted event with sql, bindings, time and a toRawSql() helper.

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

public function boot(): void
{
    if (app()->environment('local')) {
        DB::listen(function (QueryExecuted $query) {
            Log::debug('SQL', [
                'sql'  => $query->toRawSql(),
                'time' => $query->time.' ms',
            ]);
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

The environment check keeps this out of production. Raw SQL can contain personal data, and logging every query adds overhead.

How do I dump the query and stop?

Post::where('status', 'published')->dd();        // placeholders and bindings
Post::where('status', 'published')->ddRawSql();   // final SQL
Enter fullscreen mode Exit fullscreen mode

Both methods print and end the request. Use dump() and dumpRawSql() if you want the request to continue.

How do I find slow queries?

Laravel can call your closure when total query time in a request passes a limit.

use Illuminate\Database\Connection;
use Illuminate\Database\Events\QueryExecuted;

DB::whenQueryingForLongerThan(500, function (Connection $connection, QueryExecuted $event) {
    Log::warning('Slow database time in this request', ['sql' => $event->sql]);
});
Enter fullscreen mode Exit fullscreen mode

The threshold is in milliseconds. Put this call in a service provider's boot() method.

Which method should I choose?

  • toSql / toRawSql: inspect one query before it runs.
  • enableQueryLog: check what a block of code ran, such as in a test or tinker session.
  • DB::listen: log or monitor all queries in a local environment.
  • Debugbar or Telescope: a visual list during development.

What are the common mistakes?

  • Calling getQueryLog() without enabling. The array is empty.
  • Using a different connection. Enable and read the log on the same connection: DB::connection('mysql')->enableQueryLog().
  • Leaving listeners on in production. It slows requests and may log sensitive data.
  • Expecting toSql() to include values. It returns placeholders. Use toRawSql().
  • Memory growth in workers. Flush or disable the log.

How do I check that it works?

Open php artisan tinker and run:

>>> DB::enableQueryLog();
>>> App\Models\User::count();
>>> DB::getQueryLog();
Enter fullscreen mode Exit fullscreen mode

You should see one entry with a query like select count(*) as aggregate from "users".

FAQ

Does the query log work with Eloquent?

Yes. Eloquent uses the same database connection, so its queries are logged too.

Can I see queries in a test?

Yes. Enable the log at the start of the test and assert on count(DB::getQueryLog()) to guard against N+1 regressions.

Is there a built-in tool that shows queries in the browser?

Laravel Telescope and Debugbar both show them. Install either as a development dependency only.

References


Originally published on yasiramin.dev.

Top comments (0)