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.
Laravel provides two ways to debug or print the last executed query.
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', 'firstname.lastname@example.org');
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', 'email@example.com')->toSql(); dd($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', 'firstname.lastname@example.org'); 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.
Before debugging a query through the getQueryLog() method the facade class needs to import it into the controller. Below is the example
After importing the DB class facade query log needs to enable through the DB class’s enableQueryLog() method.
This method can be added anywhere but before the query that is needed to debug.
DB::enableQueryLog(); $query = User::where('email', 'email@example.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.
In this article, we have covered the following,