Handle Query Logging – Laravel 5.6

In this article, we will discuss how to handle query logging in Laravel. I’m assuming you are much familiar with the Laravel as you are reading this. Laravel optionally log all queries that have been running in the current request in memory. There is some kind of method available for this. You can check official docs for migration, also get more article on Laravel here.

Query Logging

To get an array of the executed queries, you can use getQueryLog().

$log = DB::getQueryLog();

If, you want to maintain log file in storage/logs directory. You need to update your app/Providers/AppServiceProvider.php and update the boot() function.

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use DB;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function($query) {
            Log::info(
                $query->sql,
                $query->bindings,
                $query->time
            );
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Hope you like this article. Please feel free to add the comment if any query.

 

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

LaravelLaravel EloquentQuery Logging
Comments (3)
Add Comment
  • Anatoly

    man, your code is not correct, because it do not log a time. Log::info having two arguments, you giving them three (time is third), so time is no logging.

    • Code Briefly

      Hi Anatoly, Please add more details such as code snippet, example, or reference.

  • Nikhil

    Hi,
    How can we log the queries to database so that we can create a view to check the executed queries along with the user and other summary informations