How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

Given the following code:

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

I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM users .

How do I do this?

1 Like

To output to the screen the last queries ran you can use this:

DB::enableQueryLog(); // Enable query log

// Your Eloquent query

dd(DB::getQueryLog()); // Show results of log

I believe the most recent queries will be at the bottom of the array.

You will have something like that:

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

(Thanks to Joshua’s comment below.)

Solution #:

Use the toSql() method on a QueryBuilder instance.

DB::table('users')->toSql() would return:

select * from users

This is easier than wiring up an event listener, and also lets you check what the query will actually look like at any point while you’re building it.

Refer: https://stackoverflow.com/questions/18236294/how-do-i-get-the-query-builder-to-output-its-raw-sql-query-as-a-string