Hello Laravel Friends,
Laravel is a well-crafted PHP framework that is backed up by a simple and stylish approach and supports the development of complex web apps as well. However, database queries can slow down application performance if not optimized. This tutorial will enable you to log and optimize queries in Laravel and ensure the swift running of your application in a better way.
Why is logging and optimizing queries important?
Query logging helps you identify performance bottlenecks and debug issues. Optimization also guarantees that your database interactions take place with maximum efficiency, which helps reduce load & server resource consumption. A good user experience depends heavily on both.
There are a plethora of approaches towards query optimization in Laravel. With optimized queries, the output can be maximized while the execution time is minimized. So it’s more than necessary for real-time scenarios.
Here we understand how to log and optimize our queries based on their execution time.

Steps to Log and Optimize Queries in Laravel:
Step 1: Add the below code to your app>Providers>AppServiceProvider.php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
public function boot()
{
DB::listen(function ($query) {
Log::info('SQL Query: ' . $query->sql);
Log::info('Bindings: ' . json_encode($query->bindings));
Log::info('Time: ' . $query->time . ' ms');
});
}

Step 2: Run any query of your app.
For example, here I am getting all products of specific user id (3) where collection_id is null.
$query = Product::where('user_id', 3)->whereNull('collection_id');
So this query’s log like
[2024-11-29 12:34:56] local.INFO: SQL Query: select * from `products` where `user_id` = ? and `collection_id` is null
[2024-11-29 12:34:56] local.INFO: Bindings: [3]
[2024-11-29 12:34:56] local.INFO: Time: 2.34 ms
Now, you can optimize queries based on the time taken for execution.
Conclusion:
Proper Logging and Query Optimization in Laravel is an important technique when it comes to building fast and scalable applications. Using the correct monitoring and optimizing will enable you to create a smooth experience for users.

Happy Coding!