How to get last executed mysql query in laravel 5 ?

How to get last executed mysql query in laravel 5 ?

In this post, i will tell you how to get last executed query in Laravel.

Sometime while working with laravel framework you need to see last executed query for debugging .

You can use DB::getQueryLog() function to get all executed queries if you want to get last executed then use end() method.

Before getting query log you need to first enable it by using DB::enableQueryLog() function and then you can get all executed queries.

Example :
  1. public function querylog()
  2.     {
  3.      \DB::enableQueryLog();
  4. $list = \DB::table("categories")->get();
  5. $query = \DB::getQueryLog();
  6. print_r(end($query));
  7. }
Output :
  Array ( [query] => select * from `categories` [bindings] => Array ( ) [time] => 8.09 )
  

If there are multiple DB connections then you must specify it by following way :

First you will need to enable query log for your connection :

 \DB::connection('connection1')->enableQueryLog();
 

Now you can get log for that connection :

 \DB::connection('connection1')->getQueryLog()
 

Phone: (+91) 8800417876
Noida, 201301