How to Check Query Execution Time in Laravel 10?

Spread the love

Hello Guys,

Explore this article to learn how to accurately measure query execution time in Laravel. We will guide you through the process of monitoring query execution times in Laravel, making it a comprehensive resource for those seeking a Laravel check query execution time example. In this article, you’ll find a clear example of how to keep track of query execution times in Laravel. The steps provided below will help you obtain the necessary insights into your Laravel query execution times.

This method is compatible with Laravel versions 6, 7, 8, 9, and 10, ensuring its applicability across multiple Laravel releases.

If you’re curious about how to determine SQL query execution times in Laravel, we’ve got you covered with two illustrative examples. To measure the duration of a query in Laravel, we’ll make use of the microtime() function and enableQueryLog(). This approach ensures precision in tracking query execution times.

So let’s look at some basic examples of Query Execution Time:

Example 1:

<?php
     
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Models\Post;
    
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $startTime = microtime(true);
      
        $posts = Post::get();
    
        $endTime = microtime(true);   
        $executionTime = $endTime - $startTime;
        dd("Query took " . $executionTime . " seconds to execute.");
    }
}

Output:

Query took 0.0032229423522949 seconds to execute.

Example 2:

<?php
     
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\Post;
use DB;
    
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        DB::connection()->enableQueryLog();
    
        $posts = Post::get();
    
        $queries = DB::getQueryLog();
        dd($queries);
    }
}

Output:

array:1 [ // app/Http/Controllers/PostController.php:21
  0 => array:3 [
    "query" => "select * from `posts`"
    "bindings" => []
    "time" => 1.79
  ]
]

Explore our Laravel blog section for insightful content and helpful tips.

Leave a Comment