How to Get Last Executed MySQL Query in Laravel?

10-Apr-2023

.

Admin

Hello Friends,

In this post, we will learn laravel get last executed mysql query example. This article goes in detailed on How to get the query executed in Laravel using DB::getQueryLog. This post will give you a simple example of Query Logging in Laravel. you'll learn enable query log in laravel. Let's see below example get last executed query in laravel.

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...

#Laravel

#Laravel 6