How to Log Query in Laravel

Are you looking to print the query in Laravel? Or in other words, do you want to log queries in Laravel? Both questions have slightly different answers. For printing the query, you can just print the last executed query and display it on a browser. But I would recommend you should log the query in Laravel. Doing so, your all queries will save in the log file and you can view it anytime.

In this article, I show you both options which help a user to view the queries in their Laravel application.

When you are developing a Laravel application, sometimes you may come across a situation where you need to see if the written query is correct or not. This is because of several reasons – maybe the users are not getting an expected output, you are getting a slow response from a database server, or you don’t get any output as something wrong with your query, etc. In all these scenarios, if you are logging the query then it will help to debug the issue.

How to Print Query in Laravel?

Printing the last executed query is a one time process. You may need to just print your query to the browser. It does not store the query anywhere. Below is a simple example to print your query in Laravel.

DB::enableQueryLog();
$arr_user = DB::table('users')->select('name', 'email as user_email')->get();
dd(DB::getQueryLog());

Here I have used two statements DB::enableQueryLog() and dd(DB::getQueryLog()). The first statement enables the query logging, while the second statement actually prints this log on the browser. This debugging technique also works with Laravel Eloquent.

One can use this method if they don’t want to log queries. But as said earlier this is not actually a convenient way. Because, if you follow this technique then you need to repeat these two statements DB::enableQueryLog() and dd(DB::getQueryLog()) for every query.

The better option is logging all queries in the log file.

Log Query in Laravel

I recommend a technique of logging queries in Laravel. It is a more easy and convenient way for developers. You don’t need to go to the place of each query and write the code for logging.

Instead, you only need to edit AppServiceProvider.php and you are done.

Open the app/Providers/AppServiceProvider.php file, and add 2 Facades for ‘File’ and ‘DB’ as follows.

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;

Next, in the boot() method write a below code that will log all your Laravel queries in the background.

public function boot()
{
    if(env('APP_DEBUG')) {
        DB::listen(function($query) {
            File::append(
                storage_path('/logs/query.log'),
                $query->sql . ' [' . implode(', ', $query->bindings) . ']' . PHP_EOL
           );
        });
    }
}

Now, whenever a query is executed it will log automatically in the storage/logs/query.log file. The user can directly view their queries in this query.log file.

In Laravel, one more way is available to log the queries. Using this way your query logs get stored inside the storage/logs/laravel.log file. To do so, you need to place the below code in your routes/web.php file.

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

That’s it! Now, it’s up to you to use either one of the above methods for logging the queries. You don’t need to use both methods at a time.

It’s all about logging the queries in Laravel. I hope this article will be useful for your application. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “How to Log Query in Laravel

  1. Another way (cleaner I think) to do query logging is to register a listener on app/Providers/EventServiceProvider.php

    For example:
    ‘Illuminate\Database\Events\QueryExecuted’ => [
    ‘App\Listeners\QueryExecutedListener’
    ]

    Then in your App\Listeners\QueryExecutedListener do the query logging:

    public function handle(QueryExecuted $query) {
    Log::debug(__METHOD__, [‘SQL’ => $query->sql]);
    Log::debug(__METHOD__, [‘bindings’ => $query->bindings]);
    Log::debug(__METHOD__, [‘time’ => $query->time]);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *