Simple way to Print or Get Last Executed Query in Laravel 10

Last Updated on by in Laravel

In Laravel sometimes we need to get the executed query log, first executed query or the last executed query. Sometimes, you need to debug or display SQL query via laravel query builder.

Here in this tutorial, i am going to enumerate few debugging demos with examples for executed queries in Laravel.

When you build a web application, so its highly possible, you need to print or debug last run query. However, this can be directly done in PHPMyAdmin SQL tab.

This is why in this tutorial. We are explaining how to debug SQL query from the MySQL Database query builder.

Last Query in Laravel Eloquent

It is straightforward to get the current SQL query you can do it with Laravel query builder’s toSql() method.

To propel the development performance, we don’t need to enable the query log, just execute the query as shown below.

$product = Product::where('id',77)->toSql();

Last Query in Laravel Eloquent

Now, 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.

You will notice that in this example, we are not focusing on laravel the last query, instead giving attention to getting all the query log.

$product = Product::get();
$query = DB::getQueryLog();

Debug DB Query

In this step, i will twist the ongoing approach a bit and use the end() method, although it is almost same as the before the procedure. But you can get the last query with this approach.

$product = Product::get();
$query = DB::getQueryLog();
$query = end($query);

Get Last Executed MySQL Query

Not you need to enable the debug query log and then can print all the executed queries using the following method.

public function lastExeQuery()
    $list = \DB::table("products")->get();
    $query = \DB::getQueryLog();

Here is the output you will receive in response to the above query.

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