0

To see if there's an n + 1 problem in my Laravel API, I want to see how many and which query statements were executed.

I use barryvdh/laravel-debugbar to see the query statements on web.php routes but this doesn't provide me the wanted info on api.php routes.

Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
  • 1
    I knew that way back in Laravel 5 there was the `DB::getQueryLog()` function which did exactly this. Maybe it still works? EDIT: it seems they made this a bit more easy to implement, check: https://laravel.com/docs/8.x/database#listening-for-query-events. Will also write up an answer. – Loek Oct 19 '20 at 09:48

1 Answers1

0

You can create a ServiceProvider that "listens" to all the queries being executed. You can print them on screen, write them to a log file, whatever you want.

Check https://laravel.com/docs/8.x/database#listening-for-query-events for the docs on Laravel 8.

Literal copy/paste example from the docs:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function ($query) {
            // Print it, log it, whatever :)
            // $query->sql
            // $query->bindings
            // $query->time
        });
    }
}
Loek
  • 4,037
  • 19
  • 35