Home Laravel How to Get Last Executed Query in Laravel?

How to Get Last Executed Query in Laravel?

by Shahriar Sagor

Today now in this post i would like to share with you How to Get Last Executed Query in Laravel. Sometimes We have been need to get the executed query log or we want to get the last executed query or maybe if we want to display the sql query from the laravel query builder then if we can do it that. so now i have show you three example for display executed query in Laravel application. When if we are working on laravel application at that times , so i think we need many times to print the last run query or if we want to check direct from phpmyadmin sql box. So now at that time we need to follow this three example.

so, let’s see the three example of getting sql query from the Laravel Query Builder.

Example 1:

Now in this example i will show you how we can get the directly get the current sql query by using toSql() of laravel query builder. So now in this example we don’t need to enable the query log or something so we can directly query as like bellow example:

$user = User::where('id',1)->toSql();
Example 2:

Ok good, now in this example we must need to enable query log by using DB::enableQueryLog() of Laravel Query builder. enableQueryLog() will give us access to store all execute query in cache. And we can get that query by using DB::getQueryLog(). So now in this example we will get the all query log not last only. So the bellow example how to use it together.

$user = User::get();
$query = DB::getQueryLog();
Example 3:

So now in this example i will make the same as example two, but we can get the exactly last query by using end().

So let’s see that how to use.

$user = User::get();
$query = DB::getQueryLog();
$query = end($query);

Read Also : How to convert Object into Array in PHP?

Thanks for read. I hope it help you. For more you can follow us on facebook.


You may also like