How to Check Query Execution Time in Laravel 10?

27-May-2023

.

Admin

How to Check Query Execution Time in Laravel 10?

Hi dev,

Let's look at an article on how to measure the time it takes a query to execute in Laravel. Laravel get query execution time will be taught to you. You've come to the right place if you're looking for a Laravel check query execution time example. You'll get a clear example of how to monitor the query execution time in Laravel in this article. The steps below explain how to obtain the Laravel query execution time.

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

I'll give you two examples if you're looking for information on how to determine the duration of a SQL query in Laravel. In order to determine the Laravel query execution time, we will use 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