Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Keeping a check on queries in Laravel

Being aware of the queries that are being executed in your application is one of the most important things to do if you want your application to be performant and scalable at all times.

Laravel provides a couple of ways to keep a check on your queries. Courtesy of these tweets by Laravel Backpack.

Log all the queries

The first way to keep a check on your queries is to log them.

You can use the DB::listen method to register a database queries listener to log all the queries that are executed in your application. Put the following code in your AppServiceProvider.

use Illuminate\Support\Facades\DB;

DB::listen(function ($query) {
    info($query->sql, $query->bindings, $query->time);
});

This will log queries with the binding values and the time it took to execute the query.

Log only slow queries

If you just want to log the queries that are taking longer than a certain amount of time, you can use the DB::whenQueryingForLongerThan method after enabling the query log.

use Illuminate\Support\Facades\{DB, Log};

DB::enableQueryLog();

DB::whenQueryingForLongerThan(1000, function ($connection) {
    Log::warning(
        'Long running queries detected.',
        $connection->getQueryLog()
    );
});

As you can tell, the DB::whenQueryingForLongerThan method takes a number of milliseconds as its first argument and a closure as its second argument. The closure is executed when a query takes longer than the specified number of milliseconds.

In the example above, the closure is executed when a query takes longer than 1000 milliseconds. The closure receives the connection object as its argument. You can use this object to get the query log from the connection.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?