DEV Community

Ankit Verma
Ankit Verma

Posted on

How to Get the Raw SQL Query from Laravel Query Builder

When debugging or optimizing database queries in Laravel, it's often useful to view the raw SQL query being generated. Thankfully, Laravel makes this easy with the toSql() method.

You can call toSql() on any Query Builder instance to see the SQL statement it will execute—without actually running the query.

DB::table('users')->toSql();
// Output: select * from `users`
Enter fullscreen mode Exit fullscreen mode

It also works with conditions:

User::where('status', 1)->toSql();
// Output: select * from `users` where `status` = ?
Enter fullscreen mode Exit fullscreen mode

Top comments (0)