Last Executed Query in Laravel

let’s enable the query log by taking the help of Laravel query builder’s \DB::enableQueryLog() method. The enableQueryLog() method stores all the executed queries in the cache that we can easily access with \DB::getQueryLog() method.

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

The code above will display all the related query logs while fetching the user’s records in an array format. Now by the use of the end() method, you can get the last executed query.

Now the code will be looks like this.

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

Output:

array:4 [
  "query" => "select * from `users`"
  "bindings" => []
  "time" => 5.96
]

You can get more details about this topic here.
To get to know more about Laravel, you can check these articles too.

Please follow and like us:

Related Posts

Leave a Reply

Share