How to get last executed mysql query in laravel?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello Dev’s
Today in this blog, i will teach you how we get last executed query in Laravel 8 application. So from here you can know how we get last executed query using of enableQueryLog() and getQueryLog() in laravel applications.Here i will show you how to get last executed mysql query in laravel?

So we can use DB::getQueryLog() function to get all executed queries in process. When we want to get our last executed query then we need to use end() function.

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

Example 1:

public function lastQuery()
    {
        \DB::enableQueryLog();

        $list = \DB::table("users")->get();
        $query = \DB::getQueryLog();

        dd(end($query));
    }

Output:

array:3 [
	  "query" => "select * from `users`"
	  "bindings" => []
	  "time" => 6.96
	]

If there has multiple DB connections then we must specify it by using following way:

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

Now you can get log for that connection :

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

Read Also : Laravel Replicate Model with Relationships

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

About Shahriar Sagor

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 Shahriar Sagor →