CodeBriefly
Tech Magazine

Handle Query Logging – Laravel 5.6

3 3,478

Get real time updates directly on you device, subscribe now.

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

Get real time updates directly on you device, subscribe now.

3 Comments
  1. Anatoly says

    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.

    1. Code Briefly says

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

  2. Nikhil says

    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

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More