Laravel 10 check Query Execution Time Code Example

May 27, 2023 . Admin



Hi dev,

Now, let's see an article of how to check query execution time in laravel. you will learn laravel get query execution time. if you want to see an example of laravel check query execution time then you are in the right place. This tutorial will give you a simple example of how to check query execution time in laravel. you will do the following things for how to get query execution time in laravel.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10.

I will offer you two examples if you want to know how to find the execution time of a SQL query in Laravel. To determine how long it takes a query to execute in Laravel, we'll utilise the microtime() function and enableQueryLog().

so, let's see the simple example code:

Example 1:
UserController.php
<?php
     
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Models\User;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $startTime = microtime(true);
      
        $users = User::get();
    
        $endTime = microtime(true);   
        $executionTime = $endTime - $startTime;
        dd("Query took " . $executionTime . " seconds to execute.");
    }
}	
Output:
Query took 0.0032229423522949 seconds to execute.	
Example 2: UserController.php
<?php
     
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
use DB;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        DB::connection()->enableQueryLog();
    
        $users = User::get();
    
        $queries = DB::getQueryLog();
        dd($queries);
    }
}	
Output:
array:1 [ // app/Http/Controllers/UserController.php:21
  0 => array:3 [
    "query" => "select * from `users`"
    "bindings" => []
    "time" => 1.79
  ]
]	

I hope it can help you...

#Laravel 10