DEV Community

Cover image for Laravel 8 Query Log Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 Query Log Example

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/laravel-8-query-log-example

In this post, I will show you how to implement Laravel 8 Query log. Sometimes need to show the query log and to determine what was the last executed. This is useful when you want to debug the multiple queries in your Laravel application.

In this example I will show you a 3 methods that you can apply in your project.

Example #1

$user = User::select("*")->toSql();
dd($user);
Enter fullscreen mode Exit fullscreen mode

Output:

select * from `users`
Enter fullscreen mode Exit fullscreen mode

Example #2:

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
dd($query);
Enter fullscreen mode Exit fullscreen mode

Output:

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

Example #3

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
$query = end($query);
dd($query);
Enter fullscreen mode Exit fullscreen mode

Output:

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

Example #4

\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

That's it you have now the basic on how to implement Laravel query log.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-query-log-example if you want to download this code.

Happy coding :)

Top comments (0)