How to Get Last Executed Query in Laravel 11?

By Hardik Savani September 4, 2024 Category : Laravel

In this post, I will show you how to get the last executed SQL query in a Laravel 11 application.

We will print the last SQL query in Laravel 11 using `ddRawSql()`, `toSql()`, `DB::enableQueryLog()`, and `DB::getQueryLog()`. We can use those functions in the controller to print the last executed SQL query. Let's see the one-by-one example below:

laravel 11 get last sql query

Example 1:

We can use the `ddRawSql()` Eloquent function to get the last executed query. `ddRawSql()` will return the SQL query, and you can print it.

<?php
   
namespace App\Http\Controllers;
   
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        $query = User::select("*")->ddRawSql();
            
        dd($query);
    }
}

Output:

select * from `users`

Example 2:

We can use the `toSql()` Eloquent function to get the last executed query. `toSql()` will return the SQL query, and you can print it.

<?php
   
namespace App\Http\Controllers;
   
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        $query = User::select("*")->toSql();
            
        dd($query);
    }
}

Output:

select * from `users`

Example 3:

We can use `DB::enableQueryLog()` and `DB::getQueryLog()` functions to get the last executed SQL query. `DB::enableQueryLog()` function will enable the query log, and `DB::getQueryLog()` function will return query logs.

<?php
  
namespace App\Http\Controllers;
   
use App\Models\User;
use DB;
    
class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        DB::enableQueryLog();
  
        $users = User::select("*")->get();
        $quries = DB::getQueryLog();
  
        dd($quries);
    }
}

Output:

array:1 [
  0 => array:3 [
    "query" => "select * from `users`"
    "bindings" => []
    "time" => 4.25
  ]
]

Example 4:

We can use `DB::enableQueryLog()`, `DB::getQueryLog()`, and `end()` functions to get the last executed SQL query.

<?php
  
namespace App\Http\Controllers;
   
use App\Models\User;
use DB;
    
class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        DB::enableQueryLog();
            
        $users = User::select("*")->get();
        $query = DB::getQueryLog();
  
        $query = end($query);
  
        dd($query);
    }
}

Output:

array:3 [
  "query" => "select * from `users`"
  "bindings" => []
  "time" => 2.07
]

I hope it can help you...

Shares