How to Check Query Execution Time in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hello Folks,

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, laravel 10 and laravel 11.

If you are looking for how to get sql query execution time in laravel then i will give you two examples for it. we will use microtime() function and enableQueryLog() to calculate query execution time in laravel.

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

Tags :
Shares