How to Detect Slower Queries in Laravel

Hello Artisans, today I'll show you how to detect slower queries in our Laravel Application. In Large applications like ERP level project, It's become a tough challenge for us to keep the smoothest performance. And performance is greatly depends upon the how much time need for a querying the database. So if we finds out a way that which query is takes too much time to complete its request, then it'll be much better for us to keep up the performance at the highest as possible. So, today's tutorial is based on that for detecting the slower queries in our Laravel application.

DB::whenQueryingForLongerThan() Method

Laravel provide us a handy method called whenQueryingForLongerThan(), which enable us to check which query takes more time than the specified time. So, lets' get start with our method. Open the AppServiceProvider.php and put the below code.

app/Providers/AppServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::whenQueryingForLongerThan(500, function (Connection $connection) {
            Log::warning("Database queries exceeded 5 seconds on {$connection->getName()}");
        });
    }
}

It'll save all the necessary details about the query in a Log file which will save under the Storage/logs folder.

That's it for today. Hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚