Muhammad Yasir Amin

Loading websiteโ€ฆ

More from Muhammad Yasir Amin

Build Along With Me

Practical walkthroughs on Laravel, React, APIs and deployment workflows.

Subscribe on YouTube

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

๐Ÿ› ๏ธ Laravel Tutorials4 min read

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

Muhammad Yasir Amin

Muhammad Yasir Amin

Senior Full Stack Engineerโ€ขNov 9, 2026
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.

SQL
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

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.

SQL
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

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.

JavaScript
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',
            ]);
        });
    }
}

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?

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

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.

JavaScript
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]);
});

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:

CSS
>>> DB::enableQueryLog();
>>> App\Models\User::count();
>>> DB::getQueryLog();

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

Article Index & Topic Tags
LaravelDatabaseEloquentDebugging

YouTube Channel

Build Along With Me

Practical walkthroughs on Laravel, React, APIs and deployment workflows.

Muhammad Yasir Amin
Available for Contracts
Author & Solutions Architect

Senior Full Stack Engineer

Independent Senior Full Stack Engineer working on Laravel, React and Next.js applications, APIs and delivery workflows.

Laravel & PHP ApplicationsReact & Next.js InterfacesREST APIs & IntegrationsDatabase Queries & DebuggingDocker Development WorkflowsClear Scope & Handover
Discuss Your Next Step

What Does Your Application Need Next?

Share your current system, the problem you want to solve and what a useful result looks like. We can identify the right starting point and agree on a practical scope.

Technical Audit

Find the Next Useful Fix

Application Development

Scoped, Reviewable Milestones

Ongoing Support

Agreed Capacity and Priorities

Share your goals, current stack and requirements before the call.