PHP code example of mostafaarafat / laravel-n1-detector

1. Go to this page and download the library: Download mostafaarafat/laravel-n1-detector library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mostafaarafat / laravel-n1-detector example snippets


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

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

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();
    });
});

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,
        );
    }
}

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

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

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(),
            ],
        ]);
    }
}
bash
php artisan vendor:publish --tag=n1detector-config

# 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
}