Check Query Execution Time in Laravel

In this blog, we will be going to learn about how to check query execution time in Laravel. This will be very simple and easy because there are two functions provided by Laravel. 

Two functions we will be using are microtime() function and enableQueryLog() to calculate query execution time. 


Let's start with examples,


Using microtime() function



<?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("The query took " . $executionTime . " seconds to execute.");

    }

}



Output:


The query took 0.0023445667234456 seconds to execute.


Using enableQueryLog() function


<?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 you understood how to get execution time. If you have any doubt, let me know in comnments.