Laravel Query Tracer is a good package that we can use to find exactly where a specific database query is being called in our Laravel application.

Want to optimize or debug your database queries but not sure where they're being called? See below.

Works with Clockwork:

clockwork

And works with Debugbar:

Debugbar

Requirements

Clockwork or Debugbar or your own custom query listener

Installation

Install via composer:

composer require fitztrev/query-tracer

Add the service provider to your config/app.php:

'providers' => [
    // ...
    Fitztrev\QueryTracer\Providers\QueryTracerServiceProvider::class,
],

How does it do it?

It makes use of Laravel's global query scopes to do a backtrace and find where a query originated. Then it puts that info in extraneous but helpful WHERE clauses.

By default, it's only enabled when debug is on. You can turn it off for specific models by adding this method to your model(s):

public function enableQueryTracer()
{
    return config('app.env') == 'local';
}