How to Get Query Execution Time in Laravel?
Today, We will learn How to Get Query Execution Time in Laravel. In this tutorial, you will learn how to get query execution time in Laravel. if you want to see an example of how to get query execution time in Laravel then you are in the right place.
You can use this example with laravel 7, laravel 8, laravel 9 and laravel 10.
How to Get Query Execution Time in Laravel?
If you are looking for how to find SQL query execution time in laravel, then I will give you two examples. 1. we will use microtime()
function and 2. enableQueryLog()
to calculate query execution time.
1. Use microtime()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
class EmployeeController extends Controller
{
public function index(Request $request)
{
$startTime = microtime(true);
$employee = Employee::get();
$endTime = microtime(true);
$executionTime = $endTime - $startTime;
echo "Query took " . $executionTime . " seconds to execute.";
}
}
Output:
Query took 0.0023235448692345 seconds to execute.
2. Use enableQueryLog()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
use DB;
class EmployeeController extends Controller
{
public function index(Request $request)
{
DB::connection()->enableQueryLog();
$employee = Employee::get();
$query = DB::getQueryLog();
dd($query);
}
}
Output:
array:1 [
0 => array:3 [
"query" => "select * from `employee`"
"bindings" => []
"time" => 1.32
]
]