Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/how-to-print-or-get-last-executed-query-in-laravel-8
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 this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/how-to-print-or-get-last-executed-query-in-laravel-8 if you want to download this code.
Happy coding :)
Top comments (0)