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 the query builder to output its raw SQL query as a string using PHP, then this snippet is for you. Below, we will illustrate to you two short and handy methods.

Watch a course Learn object oriented PHP

Enabling Query Log

The first solution that we recommend to use is enabling the query log. So, for outputting to the screen the last queries ran, you should run the command below:

DB::enableQueryLog(); // Enable query log 
// Your Eloquent query executed by using get() 
dd(DB::getQueryLog()); // Show results of log

After running this command, all the recent queries will appear at the bottom of the array.

It will look as follows:

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 Querybuider instance.

Here is an example:

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

The code above will return the following: select * from `users`

This method is easy while implementing Eloquent outside Laravel.