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());
Output:
select * from `users` where `email` like ?
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());
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);
Output:
select * from `users` where `email` like '%gmail.com%'
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);
});
Top comments (0)