How to Get Last Executed Query in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

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();
print_r($user);
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.

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
print_r($query);
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.

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
$query = end($query);
print_r($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.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →