How to Log Query in Laravel

Are you looking to log the query in Laravel? Or we can say, do you want to print queries in Laravel? Both questions have slightly different answers. For printing the query, you can just display the last executed query. Whereas logging means storing queries physically on the disk. Your queries will save in the log file which you can check anytime.

In this article, I show you printing and logging queries in Laravel. It’ll help you to view the queries of your Laravel application.

While working on a project, you may come across a situation where you need to see if the written query is correct or not. It happens occasionally – maybe the users are not getting an expected output, the application is getting a slow response from the database server, or you don’t get any output as something is wrong with your query. In all these scenarios, you would easily debug the issue if you are logging the queries. Sometimes, you can also find the issue by just printing the query.

How to Print Query in Laravel

Printing a query for a current request is a one-time process. You may require to print the query for quick fixes. In this case, Laravel logs the query in the memory and displays it on the browser. Below is a simple example to print your query in Laravel.

use Illuminate\Support\Facades\DB;
...
...

public function index()
{
    DB::enableQueryLog();
    $arr_user = DB::table('users')->select('name', 'email as user_email')->get();
    // same will work for Eloquent
    // $u = User::find(1);
    dd(DB::getQueryLog());
}

Now, if you run the code you will get the printed query. This technique also prints the queries executed through Eloquent.

The user can use this method if they don’t want to log queries. But it’s not a convenient way. Here, you need to repeat these two statements DB::enableQueryLog() and dd(DB::getQueryLog()) for every query. The better option is to store all queries in the log file.

Log Query in Laravel

Instead of printing, I personally preferred logging queries in Laravel. This process is convenient for developers. The benefit of query logging is you don’t need to write separate code for each query. You just have to add some code in the AppServiceProvider.php and you are done.

Open the AppServiceProvider.php file, and add the below Facades to it.

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;

Next, in the boot() method write the following code that will listen to each executed SQL query and log them in the storage/logs/query.log.

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

Now you will find all your application queries inside this storage/logs/query.log file.

Laravel also provides one more way to log queries. It stores query logs inside the storage/logs/laravel.log. For this, add the below code to your routes/web.php file.

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

That’s it! You can choose either one of the above methods for logging the queries in Laravel. I hope this article will help you in debugging problems with your Laravel 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.

3 thoughts on “How to Log Query in Laravel

  1. 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]);
    }

  2. 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 *