How to Get Last Executed Query in Laravel 10

Accessing the last executed query allows you to analyze the SQL statement and its performance.

Example 1:

Controller Code: 

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

 

Example 2:

Controller Code:

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

Example 3:

Controller Code: 

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