Table of contents

laravel query log

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);

 

Output:

select * from `users`

 

Example #2:

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
dd($query);

 

Output:

array:1 [â–¼
  0 => array:3 [â–¼
    "query" => "select * from `users`"
    "bindings" => []
    "time" => 30.66
  ]
]

 

Example #3

DB::enableQueryLog();
$user = User::get();
$query = DB::getQueryLog();
$query = end($query);
dd($query);

 

Output:

array:3 [â–¼
  "query" => "select * from `users`"
  "bindings" => []
  "time" => 22.04
]

 

Example #4

\DB::enableQueryLog();
$users = \DB::table("users")->get();
$query = \DB::getQueryLog();
dd(end($query));

 

Output:

array:3 [â–¼
  "query" => "select * from `users`"
  "bindings" => []
  "time" => 26.94
]

 

That's it you have now the basic on how to implement Laravel query log. I hope it helps. Thank you for reading :)