How to Print the Last Executed Query or Query Log in Laravel 9?

Backend developers often face issues in the queries which bring them for debugging. In Laravel, you can get the last executed query through the getQueryLog() method after enabling the query log. It belongs to the facade class that is DB.

Get Executed or Last Query Log

Laravel provides two ways to debug or print the last executed query.

  • toSql() Method
  • getQueryLog() Method

toSql() Method

This toSql() method prints the query after chaining to it. Let’s suppose a query fetches a user’s data by email.

$query = User::where('email', 'john@gmail.com');

To debug the above query all we need to do is chain the toSql() method with the query that prints the query.  Then put it into the dd() function.

$query = User::where('email', 'john@gmail.com')->toSql();
dd($query);
Print Query

It does not work with the first() and get() method so make sure you remove the function from the query for debugging purposes.

As you see it toSql() method prints query only, however for debugging the query we need binding values too. To print the binding values Laravel framework included getBindings() method. Below is a working example,

$query = User::where('email', 'john@gmail.com');
dd($query->toSql(), $query->getBindings());

Now, the above code will print the query along with binding values in the array which will be helpful to debug the query.

Print Query with Values

getQueryLog() Method

Before debugging a query through the getQueryLog() method the facade class needs to import it into the controller. Below is the example

use Illuminate\Support\Facades\DB;

After importing the DB class facade query log needs to enable through the DB class’s enableQueryLog() method.

DB::enableQueryLog();

This method can be added anywhere but before the query that is needed to debug.

DB::enableQueryLog();
$query = User::where('email', 'john@gmail.com')->get();
dd(DB::getQueryLog());

Then add the getQueryLog() right after the query that needed to be debug. getQueryLog() method returns query along with binding values and execution time in an array.

Query with Values and Execution Time

Conclusion

In this article, we have covered the following,

  • Print last executed query
  • Print query through toSql() method
  • Print query through getQueryLog() method