PHPackages                             marwen-brini/smart-query-analyzer - 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. marwen-brini/smart-query-analyzer

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

marwen-brini/smart-query-analyzer
=================================

A comprehensive query performance monitoring and optimization package for Laravel

v1.0.0(5mo ago)00MITPHPPHP ^8.3||^8.4CI failing

Since Dec 18Pushed 5mo agoCompare

[ Source](https://github.com/Marwen-Brini/smart-query-analyzer)[ Packagist](https://packagist.org/packages/marwen-brini/smart-query-analyzer)[ Docs](https://github.com/marwen-brini/smart-query-analyzer)[ GitHub Sponsors](https://github.com/Marwen-Brini)[ RSS](/packages/marwen-brini-smart-query-analyzer/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (10)Versions (2)Used By (0)

Smart Query Analyzer
====================

[](#smart-query-analyzer)

[![Latest Version on Packagist](https://camo.githubusercontent.com/fb347fabc7326be319fb6f02fe22b7e6b33c97ae2fce7dda33b7586386e96e2d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d617277656e2d6272696e692f736d6172742d71756572792d616e616c797a65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/marwen-brini/smart-query-analyzer)[![GitHub Tests Action Status](https://camo.githubusercontent.com/0c25acf24d8cf164266a47750b82f40345fd2ec85fdd530c0fce2247d828d346/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d617277656e2d6272696e692f736d6172742d71756572792d616e616c797a65722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/marwen-brini/smart-query-analyzer/actions?query=workflow%3Arun-tests+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/53646f773db0b158e2b329b69a1b8828fbe36f3f2ac4b4d33dfb449bb748278f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d617277656e2d6272696e692f736d6172742d71756572792d616e616c797a65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/marwen-brini/smart-query-analyzer)

A comprehensive query performance monitoring and optimization package for Laravel. Catch N+1 queries, identify slow queries, get index recommendations, and track performance over time.

Features
--------

[](#features)

- **N+1 Query Detection** - Automatically detect and report N+1 query patterns
- **Slow Query Detection** - Identify queries exceeding configurable thresholds with optimization suggestions
- **Index Advisor** - Get intelligent index recommendations based on query patterns
- **Query Explanation** - Analyze EXPLAIN plans with efficiency scoring
- **Performance Baselines** - Create and compare performance baselines across deployments
- **Query Budgets** - Enforce per-endpoint query limits with configurable actions
- **Trend Analysis** - Track performance trends over time with visual sparklines
- **Real-time Alerts** - Get notified about performance issues via Slack, email, or console
- **Dashboard** - Vue 3 SPA dashboard for visualizing query metrics

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

[](#requirements)

- PHP 8.3+
- Laravel 11.0+ or 12.0+

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

[](#installation)

Install the package via composer:

```
composer require marwen-brini/smart-query-analyzer --dev
```

Publish and run the migrations:

```
php artisan vendor:publish --tag="smart-query-analyzer-migrations"
php artisan migrate
```

Publish the config file:

```
php artisan vendor:publish --tag="smart-query-analyzer-config"
```

Usage
-----

[](#usage)

### Basic Setup

[](#basic-setup)

The package automatically starts monitoring queries when enabled. Add the middleware to your routes:

```
// In app/Http/Kernel.php or bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\SmartQueryAnalyzer\Http\Middleware\QueryAnalyzerMiddleware::class);
})
```

### Using the Facade

[](#using-the-facade)

```
use SmartQueryAnalyzer\Facades\SmartQueryAnalyzer;

// Start listening to queries
SmartQueryAnalyzer::startListening();

// Pause/resume logging
SmartQueryAnalyzer::pause();
SmartQueryAnalyzer::resume();

// Get captured queries and stats
$queries = SmartQueryAnalyzer::getQueries();
$stats = SmartQueryAnalyzer::getStats();

// Flush queries to database
SmartQueryAnalyzer::flush();
```

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

[](#artisan-commands)

### Analyze Queries

[](#analyze-queries)

```
# Analyze queries for a specific request
php artisan query:analyze --request-id=abc123

# Analyze queries for an endpoint
php artisan query:analyze --endpoint=/api/users --method=GET

# Analyze last N requests
php artisan query:analyze --last=10
```

### Slow Queries

[](#slow-queries)

```
# List slow queries
php artisan query:slow

# Custom threshold (ms)
php artisan query:slow --threshold=50

# Filter by endpoint
php artisan query:slow --endpoint=/api/users

# Time window
php artisan query:slow --since="1 hour ago"
```

### Query Explanation

[](#query-explanation)

```
# Explain a query interactively
php artisan query:explain "SELECT * FROM users WHERE email = 'test@example.com'"

# Output formats: table, json, raw
php artisan query:explain "SELECT * FROM users" --format=json

# From file
php artisan query:explain --file=query.sql
```

### Index Recommendations

[](#index-recommendations)

```
# Generate index recommendations
php artisan query:indexes

# Detect unused indexes
php artisan query:indexes --unused

# Generate migration file
php artisan query:indexes --migrate

# List pending recommendations
php artisan query:indexes --pending
```

### Performance Baselines

[](#performance-baselines)

```
# Create baseline for all endpoints
php artisan query:baseline --create

# Create baseline for specific endpoint
php artisan query:baseline --create --endpoint=/api/users

# List all baselines
php artisan query:baseline --list

# Export baselines to JSON
php artisan query:baseline --export=baselines.json

# Import baselines from JSON
php artisan query:baseline --import=baselines.json
```

### Regression Testing

[](#regression-testing)

```
# Test against baseline
php artisan query:test

# Custom regression threshold (percentage)
php artisan query:test --threshold=20

# Test specific endpoint
php artisan query:test --endpoint=/api/users

# CI mode with minimal output
php artisan query:test --ci

# JSON output
php artisan query:test --json
```

### Compare Performance

[](#compare-performance)

```
# Compare current vs baseline
php artisan query:compare

# Filter by commit/branch
php artisan query:compare --commit=abc123
php artisan query:compare --branch=feature/new
```

### Query Budgets

[](#query-budgets)

```
# Show budget status for all endpoints
php artisan query:budgets

# Show violations only
php artisan query:budgets --violations

# JSON output
php artisan query:budgets --json
```

### Trend Analysis

[](#trend-analysis)

```
# Show performance trends
php artisan query:trends

# Custom time period
php artisan query:trends --period=7d

# Interval: hour, day, week
php artisan query:trends --interval=hour

# JSON output
php artisan query:trends --json
```

### Dashboard Management

[](#dashboard-management)

```
# Show dashboard status
php artisan query:dashboard

# Enable/disable dashboard
php artisan query:dashboard --enable
php artisan query:dashboard --disable

# Cleanup old logs
php artisan query:dashboard --cleanup
```

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

[](#configuration)

Key configuration options in `config/smart-query-analyzer.php`:

```
return [
    // Enable/disable the analyzer
    'enabled' => env('SMART_QUERY_ANALYZER_ENABLED', true),

    // Active environments
    'environments' => ['local', 'development', 'staging'],

    // N+1 detection settings
    'n_plus_one' => [
        'enabled' => true,
        'threshold' => 5, // Occurrences before flagging
        'ignore_patterns' => [],
    ],

    // Slow query settings
    'slow_queries' => [
        'threshold' => 100, // milliseconds
        'explain_enabled' => true,
        'capture_bindings' => true,
        'capture_backtrace' => true,
    ],

    // Query budgets per endpoint
    'budgets' => [
        'enabled' => true,
        'violation_action' => 'log', // log, warn, exception
        'endpoints' => [
            '/api/users' => ['max_queries' => 10, 'max_time' => 500],
            '/api/*' => ['max_queries' => 20, 'max_time' => 1000],
        ],
        'default' => ['max_queries' => 50, 'max_time' => 2000],
    ],

    // Alert channels
    'alerts' => [
        'slow_query' => ['channels' => ['log', 'slack']],
        'n_plus_one' => ['channels' => ['log']],
    ],

    // Dashboard settings
    'dashboard' => [
        'enabled' => true,
        'path' => 'query-analyzer',
        'middleware' => ['web', 'auth'],
    ],

    // Data retention
    'storage' => [
        'retention_days' => 30,
    ],
];
```

Database Models
---------------

[](#database-models)

The package creates the following tables:

- `query_analyzer_logs` - Stores all captured queries
- `query_analyzer_n_plus_one` - N+1 detection records
- `query_analyzer_baselines` - Performance baselines
- `query_analyzer_index_recommendations` - Index suggestions

Multi-Database Support
----------------------

[](#multi-database-support)

The package supports:

- MySQL / MariaDB
- PostgreSQL
- SQLite

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Marwen-Brini](https://github.com/Marwen-Brini)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance73

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

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

Unknown

Total

1

Last Release

152d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c081aa8f05c4eec0f617cd95ebe284deea7279f694c18b084f3edfa2af992176?d=identicon)[Marwen-Brini](/maintainers/Marwen-Brini)

---

Top Contributors

[![Marwen-Brini](https://avatars.githubusercontent.com/u/23398443?v=4)](https://github.com/Marwen-Brini "Marwen-Brini (24 commits)")

---

Tags

laravelmonitoringdatabaseperformanceoptimizationn-plus-onequery-analyzerslow query

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/marwen-brini-smart-query-analyzer/health.svg)

```
[![Health](https://phpackages.com/badges/marwen-brini-smart-query-analyzer/health.svg)](https://phpackages.com/packages/marwen-brini-smart-query-analyzer)
```

###  Alternatives

[spatie/laravel-backup

A Laravel package to backup your application

6.0k21.8M191](/packages/spatie-laravel-backup)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[kreait/laravel-firebase

A Laravel package for the Firebase PHP Admin SDK

1.3k16.5M42](/packages/kreait-laravel-firebase)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[cybercog/laravel-clickhouse

ClickHouse migrations for Laravel

163166.8k](/packages/cybercog-laravel-clickhouse)

PHPackages © 2026

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