PHPackages                             zufarmarwah/laravel-performance-guard - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. zufarmarwah/laravel-performance-guard

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

zufarmarwah/laravel-performance-guard
=====================================

Production-safe performance monitoring for Laravel - detect N+1 queries, slow queries, and memory issues

v1.2.0(3mo ago)04MITPHPPHP ^8.1CI failing

Since Feb 4Pushed 3mo agoCompare

[ Source](https://github.com/zooster90/laravel-performance-guard)[ Packagist](https://packagist.org/packages/zufarmarwah/laravel-performance-guard)[ Docs](https://github.com/zooster90/laravel-performance-guard)[ Fund](https://www.buymeacoffee.com/zufarmarwah)[ GitHub Sponsors](https://github.com/zooster90)[ RSS](/packages/zufarmarwah-laravel-performance-guard/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (9)Versions (4)Used By (0)

Laravel Performance Guard
=========================

[](#laravel-performance-guard)

Production-safe performance monitoring for Laravel. Catch N+1 queries, slow queries, and performance issues before your users do.

 [![Tests](https://github.com/zooster90/laravel-performance-guard/actions/workflows/tests.yml/badge.svg)](https://github.com/zooster90/laravel-performance-guard/actions/workflows/tests.yml) [![Latest Version](https://camo.githubusercontent.com/bd1f62fa63052204e69f9c2c2d86b2d4ac3c09068a5ffab9d0f8beeedc988e6b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7a756661726d61727761682f6c61726176656c2d706572666f726d616e63652d67756172642e737667)](https://packagist.org/packages/zufarmarwah/laravel-performance-guard) [![Total Downloads](https://camo.githubusercontent.com/bb64b80b7fc35c05232aed39b0287d70d7bc5dfe3ef7d21f97f09805f37ab181/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7a756661726d61727761682f6c61726176656c2d706572666f726d616e63652d67756172642e737667)](https://packagist.org/packages/zufarmarwah/laravel-performance-guard) [![PHP Version](https://camo.githubusercontent.com/272839942f33c6a2094ddeda6e90d6057d15061ad4b47938eb90f9b5b3db09f9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f7a756661726d61727761682f6c61726176656c2d706572666f726d616e63652d67756172642e737667)](https://packagist.org/packages/zufarmarwah/laravel-performance-guard) [![License](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

---

Why Performance Guard?
----------------------

[](#why-performance-guard)

Most performance issues in Laravel apps go unnoticed until users complain. N+1 queries silently multiply, slow queries stack up, and memory usage creeps higher with every deployment.

**Performance Guard** sits in your middleware stack, monitors every request, and gives you a clear picture of what's happening -- with zero changes to your application code.

- **Drop-in middleware** -- no code changes required in your controllers or models
- **Production-safe** -- configurable sampling, async storage, and instant kill switch
- **Actionable insights** -- tells you *which* relationship to eager load, not just "you have duplicates"
- **Privacy-first** -- automatically redacts passwords, tokens, and sensitive data from recorded queries

Features
--------

[](#features)

- **N+1 Query Detection** -- detects duplicate query patterns, ignores framework tables (cache, sessions), and distinguishes eager-loading vs aggregate query suggestions
- **Slow Query Monitoring** -- identifies slow queries with optimization suggestions
- **Request Detail View** -- click any request to see all queries, duplicate patterns, and fix suggestions
- **Developer Overlay** -- floating pill on your website showing real-time queries, duration, and N+1 issues while you code (like Debugbar, but lighter)
- **Web Vitals** -- capture real user metrics (LCP, CLS, INP) from the browser and display them alongside server metrics
- **CI/CD Performance Budgets** -- `performance-guard:check` command fails your build if routes exceed duration/query thresholds or have N+1 issues
- **Performance Grading** -- grades every request A-F based on response time
- **Built-in Dashboard** -- dark-themed dashboard with auto-refresh to visualize performance metrics
- **Impact Scoring** -- routes sorted by impact (requests x avg duration) to prioritize what matters most
- **CSV Export** -- export route performance data for reporting and analysis
- **Notifications** -- alerts via Slack, Email, or Telegram when issues are detected
- **Queue Support** -- stores metrics asynchronously to avoid impacting request performance
- **Privacy First** -- automatically redacts sensitive data from recorded queries
- **Sampling** -- configurable sampling rate for high-traffic production environments
- **Auto Cleanup** -- artisan command to purge old records with configurable retention
- **High Memory Detection** -- alerts when requests exceed memory thresholds
- **Route Aggregation** -- per-route performance breakdown with controller names and impact scoring
- **Smart Filtering** -- auto-excludes redirect responses, dashboard self-monitoring, and framework table queries
- **Trend Comparison** -- period-over-period comparison showing improvement or regression
- **Artisan Status Command** -- quick terminal overview of performance health
- **Octane Compatible** -- safe for long-running processes with proper state isolation

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

[](#screenshots)

### Dashboard Overview

[](#dashboard-overview)

Stats cards with trend indicators, grade distribution, and recent requests table.

[![Dashboard Overview](docs/screenshots/dashboard-overview.png)](docs/screenshots/dashboard-overview.png)

### Route Performance

[](#route-performance)

Per-route aggregation with controller names, impact scoring, N+1/slow query issue flags, and CSV export.

[![Route Performance](docs/screenshots/routes-impact-scoring.jpg)](docs/screenshots/routes-impact-scoring.jpg)

### Request Detail -- N+1 Detection

[](#request-detail----n1-detection)

Click any request to see the full query breakdown. Duplicate query patterns are grouped with count badges, total duration, and eager-loading fix suggestions.

[![Request Detail - N+1 Detection](docs/screenshots/request-detail-n-plus-one.jpg)](docs/screenshots/request-detail-n-plus-one.jpg)

### Request Detail -- Controller &amp; Source Tracing

[](#request-detail----controller--source-tracing)

Each request shows the controller, action, user ID, IP, and source file:line for every query -- making it easy to trace exactly where queries originate.

[![Request Detail - Controller Info](docs/screenshots/request-detail-queries.jpg)](docs/screenshots/request-detail-queries.jpg)

### Request Detail -- Clean Request

[](#request-detail----clean-request)

Requests with no issues show a clean view with zero queries and status code.

[![Request Detail - Clean](docs/screenshots/request-detail-clean.jpg)](docs/screenshots/request-detail-clean.jpg)

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

[](#requirements)

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

### Database Compatibility

[](#database-compatibility)

Works with any database supported by Laravel:

DatabaseStatusMySQL / MariaDBFully testedPostgreSQLFully compatibleSQLiteFully compatible (used in test suite)SQL ServerCompatible via query builderInstallation
------------

[](#installation)

> **Note:** The Composer package name is `zufarmarwah/laravel-performance-guard`.

```
composer require zufarmarwah/laravel-performance-guard
```

Then run the install command (publishes config + runs migrations in one step):

```
php artisan performance-guard:install
```

Or install manually```
php artisan vendor:publish --tag=performance-guard-config
php artisan migrate
```

Quick Start
-----------

[](#quick-start)

### Laravel 11+ (bootstrap/app.php)

[](#laravel-11-bootstrapappphp)

To monitor **all web requests**, append the middleware globally:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->appendToGroup('web', \Zufarmarwah\PerformanceGuard\Middleware\PerformanceMonitoringMiddleware::class);
})
```

Or apply it to **specific routes** only:

```
Route::middleware(['performance-guard'])->group(function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::get('/posts', [PostController::class, 'index']);
});
```

### Laravel 10 (app/Http/Kernel.php)

[](#laravel-10-apphttpkernelphp)

Add to a middleware group or use the alias on specific routes:

```
// In Kernel.php -- monitor all web requests
protected $middlewareGroups = [
    'web' => [
        // ...existing middleware
        \Zufarmarwah\PerformanceGuard\Middleware\PerformanceMonitoringMiddleware::class,
    ],
];
```

```
// Or on specific routes
Route::middleware(['performance-guard'])->group(function () {
    // your routes
});
```

Visit `/performance-guard` in your browser. That's it.

> **Tip:** By default, data is stored synchronously so you see results immediately. For production, set `PERFORMANCE_GUARD_ASYNC=true` in your `.env` to store via queue.

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

[](#configuration)

After publishing, edit `config/performance-guard.php`:

```
return [
    // Toggle monitoring on/off
    'enabled' => env('PERFORMANCE_GUARD_ENABLED', true),

    // Monitor a percentage of requests (0.0 to 1.0)
    'sampling_rate' => env('PERFORMANCE_GUARD_SAMPLING_RATE', 1.0),

    'thresholds' => [
        'n_plus_one' => 10,        // Duplicate queries to trigger N+1 alert
        'slow_query_ms' => 300,    // Query duration threshold (ms)
        'slow_request_ms' => 1000, // Request duration threshold (ms)
        'memory_mb' => 128,        // Memory usage threshold (MB)
        'query_count' => 50,       // Total query count warning
    ],

    // Performance grading scale (duration in ms)
    'grading' => [
        'A' => 200,   //  500,   //  1000,  //  3000,  // email, [
        'admin@example.com',
    ]);
});
```

You can also restrict by IP or email whitelist:

```
'dashboard' => [
    'auth' => true,
    'allowed_ips' => ['127.0.0.1', '10.0.0.1'],
    'allowed_emails' => ['admin@example.com'],
],
```

Set `auth` to `false` for open access (not recommended in production).

Developer Overlay
-----------------

[](#developer-overlay)

A floating pill in the corner of your website that shows **real-time performance metrics** while you develop -- no tab switching needed.

```
PERFORMANCE_GUARD_OVERLAY=true
```

Then add the overlay middleware **after** the monitoring middleware:

```
// Laravel 11+ (bootstrap/app.php)
->withMiddleware(function (Middleware $middleware) {
    $middleware->appendToGroup('web', [
        \Zufarmarwah\PerformanceGuard\Middleware\PerformanceMonitoringMiddleware::class,
        \Zufarmarwah\PerformanceGuard\Middleware\PerformanceOverlayMiddleware::class,
    ]);
})
```

The overlay shows:

- Performance grade badge (A-F)
- Query count and response duration
- N+1 and slow query warnings
- Click to expand: full query list, suggestions, and link to dashboard

### Web Vitals

[](#web-vitals)

Enable browser-side metrics (LCP, CLS, INP) alongside the overlay:

```
PERFORMANCE_GUARD_WEB_VITALS=true
```

Web Vitals are captured via the Performance Observer API and sent to the dashboard automatically. No external dependencies required.

CI/CD Performance Budgets
-------------------------

[](#cicd-performance-budgets)

Stop slow code from reaching production. The `performance-guard:check` command validates recorded performance data against budgets and returns exit code 1 on failure.

```
# Check all routes against default budgets
php artisan performance-guard:check

# Custom budgets
php artisan performance-guard:check --max-duration=500 --max-queries=30

# Check a specific route
php artisan performance-guard:check --route=/api/bookings

# Fail if any N+1 issues
php artisan performance-guard:check --fail-on-n-plus-one
```

### GitHub Actions Example

[](#github-actions-example)

```
- name: Run test suite
  run: php artisan test

- name: Check performance budgets
  run: php artisan performance-guard:check --period=1h --fail-on-n-plus-one
```

Configure defaults in `config/performance-guard.php`:

```
'ci' => [
    'max_duration_ms' => 500,
    'max_queries' => 30,
    'fail_on_n_plus_one' => true,
],
```

API Endpoints
-------------

[](#api-endpoints)

All dashboard data is available as JSON:

EndpointDescription`GET /performance-guard/api`Overview stats with grade distribution`GET /performance-guard/api/{uuid}`Single record with all recorded queries (JSON)`GET /performance-guard/request/{uuid}`Request detail page with query breakdown (HTML)`GET /performance-guard/n-plus-one`N+1 issues (paginated)`GET /performance-guard/slow-queries`Slow query records (paginated)`GET /performance-guard/routes`Route-level aggregated stats (paginated)`GET /performance-guard/routes/export`Download route data as CSV`POST /performance-guard/api/vitals`Store browser Web Vitals (LCP, CLS, INP)`GET /performance-guard/api/vitals`Aggregate Web Vitals per URLAll endpoints accept a `?period=` parameter (`1h`, `24h`, `7d`, `30d`).

Notifications
-------------

[](#notifications)

Get alerted when performance issues occur.

### Slack

[](#slack)

```
PERFORMANCE_GUARD_NOTIFICATIONS=true
PERFORMANCE_GUARD_SLACK_WEBHOOK=https://hooks.slack.com/services/...
```

### Telegram

[](#telegram)

```
PERFORMANCE_GUARD_NOTIFICATIONS=true
PERFORMANCE_GUARD_TELEGRAM_TOKEN=123456:ABC-DEF...
PERFORMANCE_GUARD_TELEGRAM_CHAT_ID=-1001234567890
```

To get your bot token, message [@BotFather](https://t.me/BotFather). To get your chat ID, add the bot to a group and check `https://api.telegram.org/bot/getUpdates`.

### Email

[](#email)

```
'notifications' => [
    'enabled' => true,
    'channels' => [
        'email' => [
            'enabled' => true,
            'recipients' => ['ops@yourcompany.com'],
        ],
    ],
],
```

### Alert Types

[](#alert-types)

AlertTriggerN+1 QueriesDuplicate query pattern detectedSlow QueriesQuery exceeds duration thresholdSlow RequestRequest exceeds duration thresholdHigh MemoryMemory usage exceeds thresholdGrade FRequest received the lowest gradeA cooldown period (default: 15 minutes) prevents alert spam for the same issue.

Artisan Commands
----------------

[](#artisan-commands)

### Status

[](#status)

Get a performance overview in your terminal:

```
php artisan performance-guard:status

# Different time periods
php artisan performance-guard:status --period=1h
php artisan performance-guard:status --period=7d
php artisan performance-guard:status --period=30d
```

Shows requests, avg duration, queries, memory, N+1 count, grade distribution, and the 5 slowest routes -- all with trend indicators.

### Check (CI/CD)

[](#check-cicd)

Validate performance against budgets:

```
php artisan performance-guard:check
php artisan performance-guard:check --max-duration=500 --max-queries=30 --fail-on-n-plus-one
php artisan performance-guard:check --route=/api/bookings --period=1h
```

Returns exit code 0 (pass) or 1 (fail). See [CI/CD Performance Budgets](#cicd-performance-budgets) for setup.

### Cleanup

[](#cleanup)

Remove old records to keep your database lean:

```
# Use configured retention (default: 30 days)
php artisan performance-guard:cleanup

# Custom retention
php artisan performance-guard:cleanup --days=7

# Skip confirmation
php artisan performance-guard:cleanup --force
```

### Scheduling Cleanup

[](#scheduling-cleanup)

**Laravel 11+ (bootstrap/app.php):**

```
->withSchedule(function (\Illuminate\Console\Scheduling\Schedule $schedule) {
    $schedule->command('performance-guard:cleanup --force')->daily();
})
```

**Laravel 10 (app/Console/Kernel.php):**

```
$schedule->command('performance-guard:cleanup --force')->daily();
```

Production Deployment
---------------------

[](#production-deployment)

Recommended `.env` settings:

```
PERFORMANCE_GUARD_ENABLED=true
PERFORMANCE_GUARD_SAMPLING_RATE=0.1
PERFORMANCE_GUARD_ASYNC=true
PERFORMANCE_GUARD_QUEUE=performance
PERFORMANCE_GUARD_RETENTION_DAYS=14
```

SettingValueWhy`SAMPLING_RATE``0.1`Monitor 10% of requests -- reduces overhead while catching patterns`ASYNC``true`Recording never blocks the HTTP response`QUEUE``performance`Dedicated queue prevents competition with business jobs`RETENTION_DAYS``14`Keeps database size manageable### Emergency Kill Switch

[](#emergency-kill-switch)

Disable instantly without a deploy:

```
PERFORMANCE_GUARD_ENABLED=false
```

Or at runtime:

```
use Zufarmarwah\PerformanceGuard\Facades\PerformanceGuard;

PerformanceGuard::disable();
```

Facade
------

[](#facade)

```
use Zufarmarwah\PerformanceGuard\Facades\PerformanceGuard;

// Get stats for a period
$stats = PerformanceGuard::getStats('24h');

// Get grade distribution
$grades = PerformanceGuard::getGradeDistribution('7d');

// Toggle monitoring
PerformanceGuard::enable();
PerformanceGuard::disable();

// Check status
if (PerformanceGuard::isEnabled()) {
    // ...
}
```

How It Works
------------

[](#how-it-works)

```
Request --> Middleware --> QueryListener (DB::listen)
                              |
                        Response sent
                              |
                  NPlusOneAnalyzer (detects duplicates)
                  SlowQueryAnalyzer (finds slow queries)
                  PerformanceScorer (grades A-F)
                              |
                  StorePerformanceRecordJob (queued)
                              |
                  NotificationDispatcher (if configured)

```

1. The `performance-guard` middleware wraps each request
2. A `QueryListener` captures every SQL query via `DB::listen()`
3. After the response, analyzers process the captured data
4. Results are stored asynchronously via a queued job
5. Notifications are dispatched if thresholds are exceeded
6. Sensitive data is automatically redacted before storage

Octane Support
--------------

[](#octane-support)

Performance Guard is compatible with Laravel Octane. The `QueryListener` state is properly reset between requests to prevent data leaking across long-lived worker processes.

Testing
-------

[](#testing)

```
composer test
```

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

[](#contributing)

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/your-feature`)
3. Write tests for your changes
4. Ensure all tests pass (`composer test`)
5. Submit a pull request

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance82

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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

Every ~0 days

Total

3

Last Release

97d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ddeacd7db82bc1095755372a7be63575defe3fd6fb0e00112c3f31c26f78c122?d=identicon)[zooster90](/maintainers/zooster90)

---

Top Contributors

[![zooster90](https://avatars.githubusercontent.com/u/36158748?v=4)](https://github.com/zooster90 "zooster90 (22 commits)")

---

Tags

laravelmonitoringperformanceprofilingn-plus-oneslow-queries

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/zufarmarwah-laravel-performance-guard/health.svg)

```
[![Health](https://phpackages.com/badges/zufarmarwah-laravel-performance-guard/health.svg)](https://phpackages.com/packages/zufarmarwah-laravel-performance-guard)
```

###  Alternatives

[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[yadahan/laravel-authentication-log

Laravel Authentication Log provides authentication logger and notification for Laravel.

416632.8k5](/packages/yadahan-laravel-authentication-log)[jackwh/laravel-new-relic

Monitor your Laravel application performance with New Relic

112827.2k](/packages/jackwh-laravel-new-relic)[scoutapp/scout-apm-laravel

Scout Application Performance Monitoring Agent - https://scoutapm.com

23831.3k](/packages/scoutapp-scout-apm-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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