15 Apr

Query Logging in Laravel 5

In this tutorial, i will show you how you can see the last executed queries in Laravel 5 and how you can store their daily logs.

1. How to get executed query in Laravel 5?

Enable Query Logging

In order to retrieve the query logs, you first need to enable query logs

You need to make sure that query logging is enabled before the execution of each request. For this, you can create a middleware BeforeMiddleware in app/Http/Middleware, which will be executed before each request.
To create a middleware from artisan use the following command:

This will create a  file app/Http/Middleware/BeforeMiddleware.php. Now, after adding the above code in middleware’s handle function, the handle function should look something like this:

Retrieve Query Logs

To retrieve all the queries executed in current request you need to create a AfterMiddleware which will be executed after every request.

This will create a  file app/Http/Middleware/AfterMiddleware.php. Now, add the above code in middleware’s handle function, the handle function should look something like this:

2. Storing query logs

Now, let’s see how you can maintain a log of all executed queries in a flat file.

DB::getQueryLog() returns an array of arrays, where each array looks something like this:

In order to make the actual query we need to put the bindings in query in place of ‘?’. In

Just add the above code in the handle function of AfterMiddleware and all your daily query logs will be saved in storage/logs/query_logs  directory. 

Hope you found this article helpful. If you have any questions, feel free to ask in comments. :)

The following two tabs change content below.

Vineet Garg

Sr. Web Developer at GuestHouser
I am passionate about technology and web development.

Latest posts by Vineet Garg (see all)

  • Paige Saunders

    Couldn’t get this to do anything, are you sure a step isn’t missing?

    • http://www.techigniter.in Vineet Garg

      Hi Paige!
      I have fixed a little issue:
      Moved return $response; outside the if statement.
      But still query logging should have worked.

      Make sure you have enabled query logs in Before Middleware and try to do a
      dd($queries);
      after
      $queries = DB::getQueryLog();
      in After Middleware,
      to check if query logging is enabled or not.

  • Pingback: Log database queries globally in Laravel | Tips & Tricks()