PHPackages                             mostafaarafat/laravel-n1-detector - 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. mostafaarafat/laravel-n1-detector

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

mostafaarafat/laravel-n1-detector
=================================

Production-safe N+1 query detector for Laravel with sampling, fingerprinting, and alerting.

v1.0.0(3mo ago)33↓50%MITPHPPHP ^8.1

Since Apr 22Pushed 3mo agoCompare

[ Source](https://github.com/mostafaarafatt/laravel-n1-detector)[ Packagist](https://packagist.org/packages/mostafaarafat/laravel-n1-detector)[ RSS](/packages/mostafaarafat-laravel-n1-detector/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (1)Dependencies (8)Versions (2)Used By (0)

laravel-n1-detector
===================

[](#laravel-n1-detector)

**Production-safe N+1 query detector for Laravel.**

Detects N+1 patterns in live traffic using probabilistic sampling and SQL fingerprinting — no query logging, no privacy risk, no measurable overhead.

---

The problem
-----------

[](#the-problem)

Telescope and Debugbar catch N+1s in development. But what about the N+1 that slipped through in last Tuesday's deploy? Or the one that only manifests on large tenants with 500+ records? This package watches real production traffic and tells you when it finds one.

---

How it works
------------

[](#how-it-works)

1. On a sampled subset of requests, it hooks into `DB::listen()`.
2. Each query's literal values are stripped, leaving only its structural shape (the *fingerprint*).
3. If the same fingerprint fires ≥ N times in a single request, it's flagged as an N+1.
4. After the response is sent (`app()->terminating()`), alerts are dispatched — Slack, log, or your own handler.

Your SQL values never leave the process. Only fingerprints and counts are tracked.

---

Requirements
------------

[](#requirements)

- PHP 8.1+
- Laravel 10, 11, or 12

---

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

[](#installation)

```
composer require mostafaarafat/laravel-n1-detector
```

Publish the config:

```
php artisan vendor:publish --tag=n1detector-config
```

---

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

[](#configuration)

Add to your `.env`:

```
# Master switch. Defaults to true only in local environment.
N1_DETECTOR_ENABLED=true

# How many times the same query shape must fire to count as N+1.
N1_DETECTOR_THRESHOLD=5

# Fraction of requests to instrument. 0.05 = 5% in production.
N1_DETECTOR_SAMPLE_RATE=0.05

# Comma-separated alert channels: log, slack, null, custom
N1_DETECTOR_CHANNELS=log,slack

# Optional: Slack incoming webhook URL
N1_DETECTOR_SLACK_WEBHOOK=https://hooks.slack.com/services/...

# Optional: Slack mention on alerts
N1_DETECTOR_SLACK_MENTION=@here
```

Full config reference is in `config/n1detector.php`.

---

Usage
-----

[](#usage)

### Automatic (default)

[](#automatic-default)

The package auto-instruments all HTTP requests via the ServiceProvider. Zero code changes needed.

### Route-level middleware (selective)

[](#route-level-middleware-selective)

```
// routes/api.php
Route::middleware([\Mostafaarafat\N1Detector\Middleware\DetectN1Queries::class])
    ->group(function () {
        Route::get('/posts', [PostController::class, 'index']);
    });
```

### Queue jobs

[](#queue-jobs)

Opt in via config:

```
// config/n1detector.php
'watch_queue' => true,
```

### Artisan commands

[](#artisan-commands)

```
# Check current configuration
php artisan n1:status

# Scan a model for N+1 (great for CI)
php artisan n1:scan "App\Models\Post" --limit=50 --threshold=3

# Simulate N+1 by intentionally lazy-loading a relation
php artisan n1:scan "App\Models\Post" --relation=comments --threshold=3
```

---

Testing
-------

[](#testing)

Add the `AssertsNoN1Queries` trait to catch N+1s in your test suite — your first line of defence before production.

### With Pest

[](#with-pest)

```
uses(\Mostafaarafat\N1Detector\Testing\AssertsNoN1Queries::class);

it('loads posts index without N+1 queries', function () {
    Post::factory(20)->hasComments(5)->create();

    $this->assertNoN1Queries(
        fn() => $this->getJson('/api/posts'),
        threshold: 3,
    );
});

it('is fixed after adding eager loading', function () {
    Post::factory(20)->hasComments(5)->create();

    $this->assertNoN1Queries(function () {
        Post::with('comments')->get();
    });
});
```

### With PHPUnit

[](#with-phpunit)

```
use Mostafaarafat\N1Detector\Testing\AssertsNoN1Queries;

class PostIndexTest extends TestCase
{
    use AssertsNoN1Queries;

    public function test_no_n1_on_posts_index(): void
    {
        Post::factory(20)->hasComments(5)->create();

        $this->assertNoN1Queries(
            fn() => $this->getJson('/api/posts'),
            threshold: 3,
        );
    }
}
```

### Lower-level: inspect detections directly

[](#lower-level-inspect-detections-directly)

```
$detections = $this->runAndDetect(function () {
    $this->getJson('/api/posts');
}, threshold: 3);

expect($detections)->toHaveCount(0);
// or inspect each DetectionResult for custom assertions
```

---

Custom alert channel
--------------------

[](#custom-alert-channel)

Implement `AlertChannelInterface` and register it:

```
use Mostafaarafat\N1Detector\Contracts\AlertChannelInterface;
use Mostafaarafat\N1Detector\Data\DetectionResult;

class PagerDutyChannel implements AlertChannelInterface
{
    public function send(DetectionResult $detection): void
    {
        // fire your PagerDuty alert
        Http::post('https://events.pagerduty.com/v2/enqueue', [
            'routing_key'  => config('services.pagerduty.key'),
            'event_action' => 'trigger',
            'payload'      => [
                'summary'  => "N+1 detected: {$detection->fingerprint()}",
                'severity' => 'warning',
                'source'   => $detection->callerDescription(),
            ],
        ]);
    }
}
```

Then in `.env`:

```
N1_DETECTOR_CHANNELS=log,custom
N1_DETECTOR_CUSTOM_CHANNEL=App\Alerting\PagerDutyChannel
```

---

What it detects
---------------

[](#what-it-detects)

```
# BEFORE — triggers N+1
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->author->name; // 1 query per post
}

# AFTER — no N+1
$posts = Post::with('author')->get();
foreach ($posts as $post) {
    echo $post->author->name; // 0 extra queries
}

```

The fingerprints for the bad case:

```
select * from `posts`                                   → 1 query
select * from `users` where `id` = ?                   → N queries  ← flagged

```

The fingerprint for the good case:

```
select * from `posts`                                   → 1 query
select * from `users` where `id` in (?)                → 1 query  ← safe

```

---

Artisan scan output example
---------------------------

[](#artisan-scan-output-example)

```
$ php artisan n1:scan "App\Models\Post" --threshold=3

Scanning App\Models\Post (limit: 50, threshold: 3)...

+---------------------+-------+
| Metric              | Value |
+---------------------+-------+
| Total queries fired | 53    |
| Unique query shapes | 3     |
| N+1 detections      | 1     |
| Threshold used      | 3     |
+---------------------+-------+

1 N+1 pattern(s) detected:

  [1] Fired 50x (threshold: 3)
       Shape:  select * from `users` where `id` = ?
       From:   App\Http\Controllers\PostController@index — app/Http/Controllers/PostController.php:34
       Fix:    Add ->with('user') to your query

```

---

Production recommendations
--------------------------

[](#production-recommendations)

Environment`sample_rate``threshold``channels`local`1.0``2``log`staging`1.0``3``log,slack`production`0.05``5``log,slack`Set `deduplicate=true` (the default) in production. Without it, a single hot route with an N+1 will flood your Slack channel.

---

Architecture
------------

[](#architecture)

```
DB::listen()
    └── QueryFingerprinter      strips values → structural SQL shape
    └── RequestQueryStore       increments count per fingerprint (in-memory, no I/O)

app()->terminating()
    └── ThresholdAnalyzer       checks counts against threshold
    └── AlertDispatcher         fans out to LogChannel / SlackChannel / CustomChannel

```

The `record()` call is synchronous but does no I/O. All alerting happens after the response is sent.

---

License
-------

[](#license)

MIT

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance82

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

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

93d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5b2104ee86e384faa60bd0ee5800b917840bc409355093fee45542ab1a79ffa1?d=identicon)[mostafaarafatt](/maintainers/mostafaarafatt)

---

Tags

databasedatabase-optimizationdebuggingdeeloper-toolslaravellaravel-packagen-plus-onen1-detectorperformancephpphp-libraryproduction-safeprofilingquery-monitoringquery-optimizationsql-analyzerlaraveldatabaseperformancedetectorqueryn1-query

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mostafaarafat-laravel-n1-detector/health.svg)

```
[![Health](https://phpackages.com/badges/mostafaarafat-laravel-n1-detector/health.svg)](https://phpackages.com/packages/mostafaarafat-laravel-n1-detector)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58174.6k17](/packages/api-platform-laravel)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.6k](/packages/simplestats-io-laravel-client)[itpathsolutions/dbstan

Database Standardization and Analysis Tool for Laravel

463.0k](/packages/itpathsolutions-dbstan)

PHPackages © 2026

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