How to Print or Get Last Database Executed Query in Laravel 9?

In this quick tutorial, we will learn about how to fetch a query and the last executed query in Laravel 9 using DB Facade. DB Facades has some useful methods that can be used to get the query logs of the latest query execution. In this tutorial, I will show you a few examples to understand how it actually works.

You can print the latest query execution details by enabling the query logs in Laravel 9 using DB::enableQueryLog() and then use toSql(), and DB::getQueryLog() functions to retrieve the query log.

Let me show you how this all works with help of two simple examples.

Example 1:

let’s print a query using toSql() method.

Controller code:

<?php

namespace App\Http\Controllers;
use App\Models\User;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostController extends Controller
{
    public function index()
    {
        $query = Post::select(['title','description'])->where('id',10)->toSql();

        dd($query);
    }
}

Output:


"select `title`, `description` from `post` where id=10"

Example 2:

In the second example, we will first enable query logs by using DB::enableQueryLog() and then display the query logs of the latest executed query through DB::getQueryLog() in output.

Controller Code:

<?php

namespace App\Http\Controllers;
use App\Models\User;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostController extends Controller
{
    public function index()
    {
        DB::enableQueryLog();

       $post = Post::select(['title','description'])->where('id',10)->get();
        $queryLogs = DB::getQueryLog();

        dd($queryLogs);
    }
}

Output:

array:2 [▼
  0 => array:3 [▼
    "query" => "select `title, description` from `posts` where id=10"
    "bindings" => []
    "time" => 9.31
  ]
  1 => array:3 [▼
    "query" => "select * from `media` where `media`.`model_id` in (1, 2, 3) and `media`.`model_type` = ?"
    "bindings" => array:1 [▶]
    "time" => 1.37
  ]
]

If there are multiple Database connections then you must specify it by following way:

\DB::connection('connection_name')->enableQueryLog();

Now you can get log for that connection :

 \DB::connection('connection_name')->getQueryLog()

I hope this tutorial will give you some insight on how to use database query logs in Laravel 9.