To get or print the last executed query in Laravel, simply enable the query log using the DB::enableQueryLog()
method and print the last executed query using the DB::getQueryLog()
method.
Also, you can use toSQL()
function with a query, and print the last executed query.
How to Print or Get Last Executed Query in Laravel
Here are two ways how to enableQuery log for print or get last executed query in laravel 11, 10, and 9 apps:
Solution 1 – Get Last Query using toSQL()
To get current SQL query you can do it with Laravel query builder’s toSql()
method; as follows:
$query = User::select("*")->toSql(); dd($query);
Solution 2 – Get Last Executed Query using enableQueryLog
The easiest way to get or print the last executed query is to simply enable the query log using the DB::enableQueryLog()
method and print the last executed query using the DB::getQueryLog()
method; You can use it like this:
DB::enableQueryLog(); $users = User::select("*")->get(); $quries = DB::getQueryLog(); dd($quries);
The enableQueryLog
feature in Laravel allows developers to log and analyze the database queries executed during the execution of their application. It provides valuable insights into the queries being performed, helping with debugging, performance optimization, and understanding the interaction between the application and the database.
Note:- If you do not enable query log in Laravel and will print the last executed query then you will not get any result.
Conclusion
That’s it; You have learned how to use enableQueryLog() and getQueryLog() method to print or get the last executed query in laravel 11, 10, and 9 apps.
if you have any questions or queries then you can ask me by commenting in the comment box or you can mail us at [email protected].