W3docs

How to get the Query Builder to Output its Raw SQL Query as a String with PHP

If you want to grasp the way of getting a query builder to output its raw SQL query as a string using PHP, then you are in the right place.

If you want to get the query builder to output its raw SQL query as a string using Laravel, this snippet is for you. Below, we will illustrate two short and handy methods.

Enabling Query Log

The first solution is enabling the query log. To output the last queries run to the screen, use the following code snippet:

php enable query log

DB::enableQueryLog(); // Enable query log 
DB::table('users')->get(); // Execute a query 
dd(DB::getQueryLog()); // Show results of log

After running this code, all recent queries will appear in the array.

It will look as follows:

php query log

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

Using toSql

The second solution is using the toSql method on a Query Builder instance.

Here is an example:

php toSql

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

The code above will return the following: <kbd class="highlighted">select * from users``</kbd>

This method is straightforward for debugging queries in Laravel.