How to Check Query Execution Time in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Last Executed Query in Laravel 10?
- How to Use DB Raw Query in Laravel?
- Laravel Where Clause with Function Query Example
- How to Find Multiple Ids using Laravel Eloquent?
- Laravel Group By with Min Value Query Example
- Laravel Group By with Max Value Query Example
- Laravel Case Sensitive Query Search Example
- How to Select Custom Column with Value in Laravel Query?
- PHP Laravel Inner Join Query Example
- Laravel Eloquent whereNotBetween() Query Example
- Laravel Eloquent selectRaw() Query Example
- Laravel Has Many Through Eloquent Relationship Tutorial
- How to Redirect Route with Querystring in Laravel?
- Laravel Query Builder Where Exists Example