Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel N Plus One Detector Laravel Package

saasscaleup/laravel-n-plus-one-detector

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require saasscaleup/laravel-n-plus-one-detector
    

    Publish the config file:

    php artisan vendor:publish --provider="Saasscaleup\NPlusOneDetector\NPlusOneDetectorServiceProvider"
    
  2. First Use Case: Run the detector in your local environment:

    php artisan nplusone:detect
    

    This will scan your application for N+1 queries in real-time and log findings to storage/logs/nplusone.log.

  3. Dashboard Access: Register the middleware in app/Http/Kernel.php:

    'web' => [
        \Saasscaleup\NPlusOneDetector\Http\Middleware\NPlusOneDetector::class,
        // other middleware...
    ],
    

    Access the dashboard at /nplusone-dashboard (configured in .env).


Implementation Patterns

Workflow Integration

  1. Development Workflow:

    • Enable detection in .env:
      NPLUSONE_DETECTOR_ENABLED=true
      
    • Use the CLI command during testing:
      php artisan nplusone:detect --env=testing
      
  2. CI/CD Pipeline:

    • Add a step to run the detector in your CI pipeline (e.g., GitHub Actions):
      - name: Detect N+1 Queries
        run: php artisan nplusone:detect --env=staging
      
    • Fail the build if N+1 queries are detected (configure in config/nplusone.php):
      'fail_on_detection' => env('NPLUSONE_FAIL_ON_DETECTION', false),
      
  3. Eager Loading Patterns:

    • Use the detected relationships to manually eager load in your controllers:
      $posts = Post::with('author', 'comments.user')->get(); // Based on detector output
      
  4. Middleware-Based Detection:

    • Leverage the middleware to log N+1 queries in production (with caution):
      // app/Http/Middleware/LogNPlusOne.php
      public function handle($request, Closure $next) {
          if (app()->environment('production')) {
              \Saasscaleup\NPlusOneDetector\Facades\NPlusOneDetector::detect();
          }
          return $next($request);
      }
      

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Real-time detection adds overhead. Disable in production unless explicitly needed:
      NPLUSONE_DETECTOR_ENABLED=false
      
    • Use the CLI tool (php artisan nplusone:detect) for one-off scans.
  2. False Positives:

    • The detector may flag intentional nested loops (e.g., pagination with nested relationships). Exclude them via config:
      'ignored_routes' => [
          'posts.*', // Ignore all post-related routes
      ],
      
  3. Database-Specific Quirks:

    • Some databases (e.g., PostgreSQL with JSON fields) may trigger false positives. Adjust the ignored_queries config:
      'ignored_queries' => [
          'select * from "users" where "users".*->>\'metadata\'',
      ],
      
  4. Dashboard Access:

    • Ensure the dashboard route is protected (e.g., with auth middleware) to avoid exposing sensitive data:
      Route::middleware(['auth'])->group(function () {
          Route::get('/nplusone-dashboard', [NPlusOneDetectorController::class, 'index']);
      });
      

Debugging Tips

  1. Log Inspection:

    • Check storage/logs/nplusone.log for detailed query traces. Example entry:
      [N+1 Detected] Query: SELECT * FROM `posts` WHERE `posts`.`id` IN (1, 2, 3)
      Parent Query: SELECT * FROM `users` WHERE `users`.`id` = 1
      Relationship: posts
      
  2. Query Filtering:

    • Use the --filter flag to focus on specific routes or models:
      php artisan nplusone:detect --filter="posts.*"
      
  3. Exclusion Strategies:

    • Exclude entire controllers or methods via annotations:
      /**
       * @nplusone:ignore
       */
      public function complexReport() { ... }
      

Extension Points

  1. Custom Notifications:

    • Extend the notification system to integrate with Slack/Teams:
      // app/Providers/NPlusOneDetectorServiceProvider.php
      public function boot() {
          $this->app->make(\Saasscaleup\NPlusOneDetector\Contracts\Notification::class)
              ->extend('slack', function () {
                  return new SlackNotification();
              });
      }
      
  2. Dashboard Customization:

    • Override the dashboard views in resources/views/vendor/nplusone-detector/ to add custom metrics or charts.
  3. Query Analysis:

    • Hook into the nplusone.detected event to log custom metrics:
      \Saasscaleup\NPlusOneDetector\Events\NPlusOneDetected::class => [
          \App\Listeners\LogNPlusOneMetrics::class,
      ],
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope