'Test query execution time in laravel

How to test in laravel/phpunit how long query took to execute?

Is it possible so that it does not depend on something else?



Solution 1:[1]

The oldest way is the best one:

$start = microtime(true);
// Execute the query
$time = microtime(true) - $start;

Solution 2:[2]

Since Laravel 5.2 listen has changed to only accept one argument:

\DB::listen(function ($query) {
     // $query->sql
     // $query->bindings
     // $query->time
});

Docs: https://laravel.com/docs/5.2/database

Solution 3:[3]

You could listen to executing query like this and log the result in storage/logs/laravel.log.

\DB::listen(function ($sql, $bindings, $time) {
    \Log::info($sql, $bindings, $time);
});

You could just use $time only, but I logged $sql, $bindings, $time for the completion.

You could put this inside your AppServiceProvider.

UPDATE:

In Laravel version > 5.5 this approach is documented in the doc as listening for query events ;)

Solution 4:[4]

You can use ddd($someVar) helper starting from Laravel 6.x.

There is Queries tab which describes each query executed until ddd()

Solution 5:[5]

That's how I did it in laravel 9x.

Open app/Providers/AppServiceProvider.php put code snippet below inside boot method:

DB::listen(function ($query) {
    Log::info($query->sql);     // the query being executed
    Log::info($query->time);    // query time in milliseconds
});

Then check the log file for the details in storage/logs/laravel.log.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexey Mezenin
Solution 2 Sajidur Rahman
Solution 3
Solution 4 Samir Mammadhasanov
Solution 5 Sajidur Rahman