PHPackages                             mashiur-softzino/laravel-query-debugger - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. mashiur-softzino/laravel-query-debugger

ActiveLibrary[Database &amp; ORM](/categories/database)

mashiur-softzino/laravel-query-debugger
=======================================

Auto-detect N+1 queries, slow queries and suggest optimizations for Laravel Eloquent

v1.0.0(3mo ago)03MITPHPPHP ^8.2

Since Jan 20Pushed 3mo agoCompare

[ Source](https://github.com/mashiur-softzino/laravel-query-debugger)[ Packagist](https://packagist.org/packages/mashiur-softzino/laravel-query-debugger)[ Docs](https://github.com/mash/laravel-query-debugger)[ RSS](/packages/mashiur-softzino-laravel-query-debugger/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (13)Versions (2)Used By (0)

Laravel Query Debugger
======================

[](#laravel-query-debugger)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b0851ae2bed3b274a1fcd6c2cff3b421d9d70da6101992542d8dd5aea7dda700/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6173686975722d736f66747a696e6f2f6c61726176656c2d71756572792d64656275676765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mashiur-softzino/laravel-query-debugger)[![GitHub Tests Action Status](https://camo.githubusercontent.com/9aedeede991b1b2671aec6ffa88ce212b3f30a044db076f1ced2bd1c4f9e1293/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d6173686975722d736f66747a696e6f2f6c61726176656c2d71756572792d64656275676765722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mashiur-softzino/laravel-query-debugger/actions?query=workflow%3Arun-tests+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/0e9ae180a5eb851bde7f067437127796274a2fb6cdee1e4a89c5a1b1bc54dd22/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6173686975722d736f66747a696e6f2f6c61726176656c2d71756572792d64656275676765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mashiur-softzino/laravel-query-debugger)

**Auto-detect N+1 queries, duplicate queries, slow queries, and get actionable optimization suggestions for your Laravel Eloquent queries.**

Stop wasting hours debugging query performance! This package automatically detects N+1 query problems, identifies slow queries, duplicate queries, SELECT \* issues, and provides you with exact code suggestions to fix them.

Features
--------

[](#features)

- **Visual Debug Toolbar** - Laravel Debugbar-like toolbar at the bottom of your page (works with Blade, Inertia, Vue, React)
- **Performance Score** - Get a score (0-100) with grades (A+, A, B, C, D, F) for your page's query performance
- **Automatic N+1 Detection** - Catches N+1 query patterns and tells you exactly where they occur
- **Duplicate Query Detection** - Finds exact same queries running multiple times
- **SELECT \* Warnings** - Identifies queries fetching all columns unnecessarily
- **Slow Query Identification** - Flags queries exceeding your performance thresholds
- **Actionable Suggestions** - Get before/after code examples to fix issues
- **Context Tracking** - Know exactly which file and line triggered each query
- **Beautiful Reports** - Export detailed HTML or JSON reports
- **Zero Config** - Works out of the box with sensible defaults
- **Production Safe** - Automatically disabled in production
- **Framework Agnostic** - Works with Blade, Inertia.js, Vue.js, React, and any SPA

Screenshots
-----------

[](#screenshots)

### Visual Debug Toolbar (Collapsed)

[](#visual-debug-toolbar-collapsed)

```
┌─────────────────────────────────────────────────────────────────────┐
│ ⚡ Query Debugger │ Queries: 12 │ Time: 45ms │ N+1: 2 │ ▲ Expand   │
└─────────────────────────────────────────────────────────────────────┘

```

### Visual Debug Toolbar (Expanded)

[](#visual-debug-toolbar-expanded)

```
┌─────────────────────────────────────────────────────────────────────┐
│ PERFORMANCE SCORE: 75/100 (C - Needs Improvement)                   │
├─────────────────────────────────────────────────────────────────────┤
│ Statistics          │ N+1 Issues           │ Other Issues           │
│ Total Queries: 12   │ 🚨 Issue #1          │ 🔄 Duplicate Query #1  │
│ Total Time: 45ms    │ Pattern: SELECT...   │ 3x executed            │
│ Avg Time: 3.75ms    │ Count: 5 queries     │ ⚠️ SELECT * Query #1   │
│                     │ 💡 Use eager loading │                        │
└─────────────────────────────────────────────────────────────────────┘

```

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require mashiur-softzino/laravel-query-debugger --dev
```

The package will automatically register itself via Laravel's auto-discovery.

Configuration
-------------

[](#configuration)

Publish the configuration file (optional):

```
php artisan vendor:publish --tag="query-debugger-config"
```

This will create a `config/query-debugger.php` file where you can customize:

```
return [
    'enabled' => env('QUERY_DEBUGGER_ENABLED', env('APP_DEBUG', false)),
    'slow_threshold' => 500,      // ms
    'critical_threshold' => 1000, // ms
    'n1_threshold' => 5,          // how many repeated queries = N+1
    // ... more options
];
```

### Environment Variables

[](#environment-variables)

Add these to your `.env` file:

```
QUERY_DEBUGGER_ENABLED=true
QUERY_DEBUGGER_SLOW_THRESHOLD=500
QUERY_DEBUGGER_N1_THRESHOLD=5
```

Usage
-----

[](#usage)

### Visual Debug Toolbar (Recommended)

[](#visual-debug-toolbar-recommended)

The package automatically injects a debug toolbar at the bottom of your HTML pages. No configuration needed!

**Features:**

- Collapsible/expandable panel
- Drag to resize
- Performance score with grade (A+, A, B, C, D, F)
- N+1 issue details with fix suggestions
- Duplicate query detection
- SELECT \* warnings
- Works with all frontend frameworks (Blade, Inertia, Vue, React)

### Middleware Setup

[](#middleware-setup)

Add the middleware to see the toolbar. In `app/Http/Kernel.php`:

```
protected $middlewareGroups = [
    'web' => [
        // ...
        \Mash\LaravelQueryDebugger\Middleware\QueryDebuggerMiddleware::class,
    ],
];
```

Or for Laravel 11+ in `bootstrap/app.php`:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \Mash\LaravelQueryDebugger\Middleware\QueryDebuggerMiddleware::class,
    ]);
})
```

### Command Line Usage

[](#command-line-usage)

```
php artisan debug:queries
```

You'll get a beautiful console output showing:

```
🔍 Analyzing Database Queries...

Total Queries .................................................. 45
Total Time ................................................... 1250ms
Average Time ................................................. 27.8ms
Slow Queries ................................................. 3

❌ N+1 Query Problems Detected

Issue #1: posts table
  Query Count ............................................... 10
  Total Time ................................................ 450ms
  Avg Time .................................................. 45ms
  Location ................... app/Http/Controllers/UserController.php:25

  💡 Suggestion:
     Add eager loading: use ->with('posts') on your parent query.

```

### Command Options

[](#command-options)

```
# Show queries slower than 300ms
php artisan debug:queries --slow=300

# Show all queries (not just issues)
php artisan debug:queries --all

# Export report to JSON
php artisan debug:queries --export=json

# Export report to HTML
php artisan debug:queries --export=html

# Hide fix suggestions
php artisan debug:queries --no-suggestions
```

### Using the Facade

[](#using-the-facade)

You can also interact with the query logger programmatically:

```
use Mash\LaravelQueryDebugger\Facades\QueryDebugger;

// Get all logged queries
$queries = QueryDebugger::getQueries();

// Get only slow queries
$slowQueries = QueryDebugger::getSlowQueries(500);

// Get statistics
$stats = QueryDebugger::getStatistics();
// [
//     'total_queries' => 45,
//     'total_time' => 1250.5,
//     'avg_time' => 27.8,
//     'slow_queries' => 3,
//     ...
// ]

// Clear logged queries
QueryDebugger::clear();
```

Performance Scoring
-------------------

[](#performance-scoring)

The package calculates a performance score (0-100) based on:

FactorImpactTotal queries &gt; 10-5 pointsTotal queries &gt; 20-10 pointsTotal time &gt; 100ms-5 pointsTotal time &gt; 500ms-15 pointsEach N+1 issue-15 points (max -30)Each duplicate query-5 points (max -15)Each SELECT \* query-2 points (max -10)Slow queries-5 points each (max -15)### Grade Scale

[](#grade-scale)

ScoreGradeLabel95-100A+Excellent85-94AGood70-84BNeeds Improvement50-69CPoor25-49DVery Poor0-24FCriticalReal-World Examples
-------------------

[](#real-world-examples)

### N+1 Problem Detection

[](#n1-problem-detection)

**Your Code:**

```
// ❌ This creates an N+1 problem
public function index()
{
    $users = User::all();

    foreach ($users as $user) {
        echo $user->posts->count(); // Queries posts for each user!
    }
}
```

**Package Output:**

```
❌ N+1 Detected at app/Http/Controllers/UserController.php:15
- Queries: 1 (User) + 10 (Posts per User) = 11 total
- Time: 750ms
- Suggestion: Add ->with('posts') to your User query

💡 Fix:
$users = User::with('posts')->get();

```

**Fixed Code:**

```
// ✅ Optimized with eager loading
public function index()
{
    $users = User::with('posts')->get();

    foreach ($users as $user) {
        echo $user->posts->count(); // No additional queries!
    }
}
```

### Duplicate Query Detection

[](#duplicate-query-detection)

**Your Code:**

```
// ❌ Same query runs multiple times
public function dashboard()
{
    $user = User::find(1);
    // ... later in code ...
    $user = User::find(1); // Same query again!
}
```

**Package Output:**

```
🔄 Duplicate Query Detected
SQL: SELECT * FROM users WHERE id = 1
Executions: 2x
Wasted Time: 15ms

💡 Suggestion:
Store the result in a variable and reuse it, or use caching.

```

### SELECT \* Warning

[](#select--warning)

**Your Code:**

```
// ❌ Fetching all columns when you only need a few
$users = User::all();
```

**Package Output:**

```
⚠️ SELECT * Query Detected
SQL: SELECT * FROM users
Location: app/Http/Controllers/UserController.php:10

💡 Better approach:
User::select(['id', 'name', 'email'])->get()

```

Configuration Reference
-----------------------

[](#configuration-reference)

### Thresholds

[](#thresholds)

```
'slow_threshold' => 500,      // Queries > 500ms flagged as slow
'critical_threshold' => 1000, // Queries > 1000ms flagged as critical
'n1_threshold' => 5,          // Pattern repeats 5+ times = N+1
```

### Detection Settings

[](#detection-settings)

```
'detection' => [
    'n1' => true,              // Detect N+1 problems
    'duplicate' => true,       // Detect duplicate queries
    'select_all' => true,      // Detect SELECT * queries
],
```

### Middleware Settings

[](#middleware-settings)

```
'middleware' => [
    'auto_enable' => true,
    'exclude_paths' => [
        '_debugbar/*',
        'telescope/*',
        'horizon/*',
    ],
],
```

### Context Tracking

[](#context-tracking)

```
'track_context' => true, // Track file/line for each query
```

> **Note:** Uses `debug_backtrace()` which has performance overhead. Automatically disabled in production.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Mashiur Rahman](https://github.com/mashiur-softzino)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Support
-------

[](#support)

If you find this package helpful, please consider giving it a ⭐ on GitHub!

For issues or questions, please open an issue on [GitHub](https://github.com/mashiur-softzino/laravel-query-debugger/issues).

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance79

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

112d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a06e6319a2c72a0e45f1e95fb656e61ebd56d1c5d747667d6e1dcb11d32e8b0d?d=identicon)[mashiur-softzino](/maintainers/mashiur-softzino)

---

Top Contributors

[![mashiur-softzino](https://avatars.githubusercontent.com/u/241680062?v=4)](https://github.com/mashiur-softzino "mashiur-softzino (3 commits)")

---

Tags

laravelperformanceeloquentquerydebuggeroptimization

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mashiur-softzino-laravel-query-debugger/health.svg)

```
[![Health](https://phpackages.com/badges/mashiur-softzino-laravel-query-debugger/health.svg)](https://phpackages.com/packages/mashiur-softzino-laravel-query-debugger)
```

###  Alternatives

[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[lacodix/laravel-model-filter

A Laravel package to filter, search and sort models with ease while fetching from database.

17649.9k](/packages/lacodix-laravel-model-filter)[elipzis/laravel-cacheable-model

Automatic query-based model cache for your Laravel app

15546.1k](/packages/elipzis-laravel-cacheable-model)[jerome/filterable

Streamline dynamic Eloquent query filtering with seamless API request integration and advanced caching strategies.

19226.1k](/packages/jerome-filterable)[sarfraznawaz2005/indexer

Laravel package to monitor SELECT queries and offer best possible INDEX fields.

562.7k](/packages/sarfraznawaz2005-indexer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
