Laravel raw query: how to get it from the SQL builder

Sometimes you want to know the exact Laravel raw query – the SQL output string executed under the hood – for a given instance of the database Query Builder.

Let’s say you have this query:

DB::table('users')->get();

You can get the raw SQL query string that the query builder above will generate in at least two ways:

  1. use the toSql() function
  2. use the enableQueryLog() function

Solution 1: the toSql() function

Replace the query builder get() call with a toSql() call and echo it, like this:

echo DB::table('users')->toSql();

Laravel will return:

select * from users

Solution 2: the enableQueryLog() function

Enable the query log, prepending the query builder call with this line:

DB::enableQueryLog();

Then, add a line like this AFTER the query builder call:

dd(DB::getQueryLog());

Laravel will return:

array(1) {
 [0]=>
  array(3) {
   ["query"]=>
    string(21) "select * from "users""
   ["bindings"]=>
    array(0) {}
   ["time"]=>
    string(4) "0.71"
  }
}

2023 update: know the Laravel raw query using the toRawSql() function

Laravel 10.15 got a long-awaited feature, to get the raw SQL including bindings. It works like this:

User::where(...)->toRawSql()

This statement prints the generated SQL query with bindings embedded safely into the query. Chris Fidao wrote a good insight about this new feature.

If you need the raw query while investigating a Gateway error, check this guide for debugging Gateway errors.

Leave a Reply

Your email address will not be published. Required fields are marked *