Table of contents
In this post, I will show you how to print or get the last executed query in your Laravel 8 application. Sometimes we need to do this to log or debug and determine what is the performance of our queries.
Â
Luckily Laravel provides a method to get the last executed query and I will show you how.
Â
Get Last Query in Laravel Eloquent
In this example, we will just add toSql() method to our eloquent query. See the below example:
$user = User::where('id',1)->toSql();
dd($user);
Â
See below output:
"select * from `users` where `id` = ?"
Â
Log Last Query in Laravel Eloquent
In this method, we will log our last Laravel eloquent query. See below example code:
DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
dd($query);
Â
Sample output:
array:1 [â–¼
0 => array:3 [â–¼
"query" => "select * from `users`"
"bindings" => []
"time" => 30.66
]
]
Â
Debug the Last Laravel Eloquent Query
In this sample, we will debug the last Laravel eloquent query. See below code:
DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
$query = end($query);
dd($query);
Â
Sample output:
array:3 [â–¼
"query" => "select * from `users`"
"bindings" => []
"time" => 22.04
]
Â
Get/Print Last Executed MySQL Query
In this section, we will get/print the last executed MySQL query. See the following example:
\DB::enableQueryLog();
$users = \DB::table("users")->get();
$query = \DB::getQueryLog();
dd(end($query));
Â
Output:
array:3 [â–¼
"query" => "select * from `users`"
"bindings" => []
"time" => 26.94
]
Â
Now you have an idea of how to log/debug the last executed query in your Laravel application. I hope it helps.
Read next