How to log query in laravel

By | May 17, 2021

To log a query in laravel there are multiple methods available. I am going to share one of the method log query in laravel.

Why we have required to log queries? Sometimes we are not getting correct results when we are running our application. Sometime not able to figure out issue. We have requirement to check the query what is running in the backend. So we need query which can be get by logging in laravel. To log query in laravel follow the below steps.

  1. Open the AppServiceProvider.php file you can found app/Providers/AppServiceProvider.php on the path.
  2. Add the following code to log query in laravel
        \DB::listen(function($sql) {
            \Log::info('SQL', [$sql->sql]);
            \Log::info('Query parameters', [$sql->bindings]);
            \Log::info('Query execution time', [$sql->time]);
        });

The above code will log queries executed on the page, their parameters and the execution time as well in the log file. All the queries in the laravel logged by above code in the log file. You can add condition as per your choice or requirement. If you want to log only specific query you can add this code to your desired place to log the query.

For more information to log query in laravel you can refer to https://laravel.com/docs/8.x/database#listening-for-query-events

One other option I would like to recommend to use telescope. https://laravel.com/docs/8.x/telescope#introduction

Leave a Reply