How to get last executed mysql query in laravel 6 ?

Laravel 6 , Laravel

Nicesnippets

130

21-09-2019


In this blog, i will show you how to get last executed query in Laravel 6. you can get last executed query using enableQueryLog() and getQueryLog() in laravel 6.

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

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 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 are multiple Database connections then you must specify it by following way:

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

Now you can get log for that connection :

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

It will help you...