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 Query Detector Laravel Package

beyondcode/laravel-query-detector

Detect N+1 query issues in Laravel during development. Monitors database queries in real time and alerts you when repeated queries suggest missing eager loading, helping you optimize performance and reduce unnecessary database calls.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Low-Coupling Design: The package leverages Laravel’s service provider pattern and event system (QueryDetected event), making it non-intrusive to existing architecture. It hooks into the query builder without modifying core Eloquent logic, ensuring backward compatibility.
  • Observability-First: Aligns with modern Laravel observability stacks (Debugbar, Clockwork, JSON responses) and integrates seamlessly with logging systems (Monolog, Sentry). Ideal for SRE-driven teams prioritizing debuggability.
  • Modular Outputs: Supports multiple notification channels (alerts, console, logs, Debugbar), allowing flexible adoption based on team workflows (e.g., devs prefer console output; PMs track via logs).
  • Laravel Ecosystem Synergy: Works natively with Eloquent relationships, query scopes, and API resources, making it a natural fit for Laravel-heavy applications (e.g., SaaS platforms, marketplaces, or CMS backends).

Integration Feasibility

  • Zero-Config for Basic Use: Automatically activates in debug mode, requiring no manual setup for initial trials. Reduces friction for PoCs or quick wins.
  • Config-Driven Customization: Allows fine-grained control via querydetector.php (e.g., whitelisting relations, adjusting thresholds, or disabling in production). Supports environment-specific tuning (e.g., stricter checks in staging).
  • Event-Driven Extensibility: Emits QueryDetected events, enabling custom integrations (e.g., Slack alerts, Datadog metrics, or automated PR comments via GitHub API). Example:
    Event::listen(\BeyondCode\QueryDetector\Events\QueryDetected::class, function ($event) {
        report(new \App\Events\NPlusOneQueryDetected($event->query));
    });
    
  • Lumen Support: Explicitly designed for micro-services, ensuring lightweight adoption in API-only or serverless Laravel deployments.

Technical Risk

Risk Mitigation Strategy Impact
False Positives Configurable threshold (default: 1) and whitelisting reduce noise. Low (tunable via .env).
Performance Overhead Only active in debug mode; minimal runtime cost (sub-millisecond per request). Negligible.
Debugbar Dependency Optional; fallback to logs/console if Debugbar isn’t installed. Medium (but non-blocking).
Laravel Version Lock Actively maintained for Laravel 5.8–12.x; backward-compatible via composer. Low (supports legacy and modern).
Custom Outputs Requires basic PHP knowledge to extend (e.g., creating a new Output class). Medium (documented in README).

Key Questions for TPM

  1. Adoption Scope:

    • Should this be mandatory for all devs (via CI gates) or optional (self-service)?
    • Example: Enforce in feature branches but allow opt-out in legacy codebases.
  2. Output Strategy:

    • Should we prioritize alerts (blocking UI) or logs/JSON (async processing)?
    • Tradeoff: Alerts are immediate but disruptive; logs enable historical analysis.
  3. Threshold Tuning:

    • What’s the acceptable N+1 rate for your app? (e.g., threshold=5 for high-traffic APIs).
    • Risk: Too low → alert fatigue; too high → missed optimizations.
  4. Integration with Observability:

    • Should QueryDetected events feed into existing tools (e.g., Sentry, Datadog, or custom dashboards)?
    • Example: Auto-create Jira tickets for recurring N+1 queries.
  5. Production Readiness:

    • Should the package be disabled in production (default) or enabled with stricter thresholds?
    • Consider: Some apps (e.g., real-time systems) may need runtime monitoring.
  6. Legacy Code Impact:

    • How will this affect monolithic apps with deeply nested relationships?
    • Mitigation: Start with whitelisting critical paths, then expand.

Integration Approach

Stack Fit

  • Laravel Core: Seamlessly integrates with Eloquent, Query Builder, and HTTP lifecycle (middleware-like behavior).
  • Debugging Tools:
    • Debugbar: Enhances dev workflows with visual query warnings.
    • Clockwork: Provides request-level insights for performance tuning.
    • JSON Output: Useful for API-driven teams (e.g., frontend devs debugging GraphQL).
  • Logging Systems: Works with Monolog, Sentry, or ELK stacks for centralized monitoring.
  • CI/CD: Can be gated in PRs (e.g., fail builds with N+1 queries) via GitHub Actions or GitLab CI.

Migration Path

  1. Pilot Phase (1–2 Sprints):

    • Install in dev/staging (composer require --dev).
    • Enable console/alert outputs for immediate feedback.
    • Goal: Identify top 5–10 N+1 hotspots.
  2. Configuration Tuning:

    • Adjust threshold and except in querydetector.php.
    • Whitelist known-safe relations (e.g., User::posts() if cached).
  3. Output Optimization:

    • Replace alerts with JSON/logs for APIs.
    • Integrate with Debugbar for frontend teams.
  4. Automation (Optional):

    • Add CI checks (e.g., php artisan query:detect --fail-on=5).
    • Set up Slack/Sentry alerts for critical paths.
  5. Production Rollout:

    • Disable in production (default) or enable with higher thresholds.
    • Monitor via logs/metrics (e.g., Datadog dashboard).

Compatibility

Component Compatibility Notes
Laravel Versions 5.8–12.x (tested) Uses feature flags for version support.
PHP Versions 7.4–8.2 (via Laravel support) No direct PHP constraints.
Debugbar v3–v4 (with runtime resolution) Fallback to logs if missing.
Clockwork Supported (requires itsgoingd/clockwork) Optional dependency.
Lumen Explicit support via LumenQueryDetectorServiceProvider Lightweight integration.
Custom Outputs Extendable via Output interface Requires ~10 lines of PHP.

Sequencing

  1. Pre-Reqs:

    • Ensure Laravel 8+ (for PHP 8+ features).
    • Install Debugbar/Clockwork if desired (optional).
  2. Installation:

    composer require beyondcode/laravel-query-detector --dev
    php artisan vendor:publish --provider="BeyondCode\QueryDetector\QueryDetectorServiceProvider"
    
  3. Configuration:

    • Set threshold (e.g., QUERY_DETECTOR_THRESHOLD=3).
    • Whitelist relations in config/querydetector.php.
  4. Testing:

    • Trigger N+1 queries in dev mode (e.g., User::with('posts')->get() without eager loading).
    • Verify alerts/logs appear.
  5. Scaling:

    • Add custom event listeners for advanced use cases.
    • Integrate with monitoring tools (e.g., Prometheus metrics).

Operational Impact

Maintenance

  • Low Overhead:
    • No database migrations or schema changes required.
    • Zero runtime impact in production (disabled by default).
  • Dependency Updates:
    • Follow Laravel’s release cycle (e.g., test with Laravel 12 before upgrading).
    • Monitor BeyondCode’s release notes for breaking changes.
  • Configuration Drift:
    • Centralized in config/querydetector.php; easy to audit.
    • Use environment variables for dynamic tuning (e.g., QUERY_DETECTOR_THRESHOLD).
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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