DEV Community

Ankit Verma
Ankit Verma

Posted on

How do I get the query builder to output its raw SQL query as a string?

How to Get the Raw SQL Query from Laravel’s Query Builder

While working with Laravel’s Query Builder or Eloquent, there are times when you just want to see the actual SQL query being generated—especially when debugging complex queries.

Laravel provides a clean and simple way to do this.


Get the Raw SQL (with placeholders)

Use the toSql() method to view the generated SQL:

$query = User::where('email', 'like', '%gmail.com%');

dd($query->toSql());
Enter fullscreen mode Exit fullscreen mode

Output:

select * from `users` where `email` like ?
Enter fullscreen mode Exit fullscreen mode

This shows the query with ? placeholders instead of real values.

Get the Query Bindings
To see the values bound to the placeholders:

dd($query->getBindings());
Enter fullscreen mode Exit fullscreen mode

Get the Full SQL Query (Debugging Only)
If you want to see the SQL with actual values filled in:

$sql = vsprintf(
    str_replace('?', "'%s'", $query->toSql()),
    $query->getBindings()
);

dd($sql);
Enter fullscreen mode Exit fullscreen mode

Output:

select * from `users` where `email` like '%gmail.com%'
Enter fullscreen mode Exit fullscreen mode

This method is for debugging or logging only. Do not use it to execute queries.

Bonus: Log All SQL Queries
You can log every SQL query executed by Laravel:

DB::listen(function ($query) {
    logger($query->sql, $query->bindings);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)