DEV Community

Cover image for How to Print or Get Last Executed Query in Laravel 8
Code And Deploy
Code And Deploy

Posted on

How to Print or Get Last Executed Query in Laravel 8

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); 
Enter fullscreen mode Exit fullscreen mode

See below output:

"select * from `users` where `id` = ?" 
Enter fullscreen mode Exit fullscreen mode

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); 
Enter fullscreen mode Exit fullscreen mode

Sample output:

array:1 [▼ 0 => array:3 [▼ "query" => "select * from `users`" "bindings" => [] "time" => 30.66 ] ] 
Enter fullscreen mode Exit fullscreen mode

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); 
Enter fullscreen mode Exit fullscreen mode

Sample output:

array:3 [▼ "query" => "select * from `users`" "bindings" => [] "time" => 22.04 ] 
Enter fullscreen mode Exit fullscreen mode

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)); 
Enter fullscreen mode Exit fullscreen mode

Output:

array:3 [▼ "query" => "select * from `users`" "bindings" => [] "time" => 26.94 ] 
Enter fullscreen mode Exit fullscreen mode

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)