PHPackages                             gladehq/laravel-query-lens - 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. gladehq/laravel-query-lens

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

gladehq/laravel-query-lens
==========================

A Laravel package for analyzing and optimizing database queries with performance insights

v1.0.0(4mo ago)2191MITPHPPHP ^8.1CI passing

Since Feb 8Pushed 4mo agoCompare

[ Source](https://github.com/gladehq/laravel-query-lens)[ Packagist](https://packagist.org/packages/gladehq/laravel-query-lens)[ RSS](/packages/gladehq-laravel-query-lens/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (3)Dependencies (8)Versions (4)Used By (0)

QueryLens
=========

[](#querylens)

**The self-hosted query performance platform for Laravel -- with AI-powered optimization, automated index recommendations, and CI pipeline regression detection.**

[![PHP Version](https://camo.githubusercontent.com/238fba3290320e81452233068c0cb0a7cce85d4244efe03b6182610765be27e3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f676c61646568712f6c61726176656c2d71756572792d6c656e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/gladehq/laravel-query-lens)[![Laravel Version](https://camo.githubusercontent.com/7c468061448b76d7ad21d0366d25630b1e0168b1f8fd2afb06911b7f0274fc93/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d31302e7825323025374325323031312e7825323025374325323031322e782d626c75653f7374796c653d666c61742d737175617265)](https://packagist.org/packages/gladehq/laravel-query-lens)[![Tests](https://camo.githubusercontent.com/d2d9e296f08f56bf408262b298e35521365b34e906a84b9d1d74ee7bd2a4ca32/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d37323025323070617373696e672d627269676874677265656e3f7374796c653d666c61742d737175617265)](https://github.com/gladehq/laravel-query-lens)[![Latest Version on Packagist](https://camo.githubusercontent.com/e73f2e19c9effe483b86ee79cb829e82195ace5d714985682da7c4acd872ebf0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f676c61646568712f6c61726176656c2d71756572792d6c656e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/gladehq/laravel-query-lens)[![License](https://camo.githubusercontent.com/659520c9d1e580ea0955171124f126487a22b747b917444dba7cab43a4c99f21/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f676c61646568712f6c61726176656c2d71756572792d6c656e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/gladehq/laravel-query-lens)

---

Why QueryLens
-------------

[](#why-querylens)

- **Self-hosted.** Your query data never leaves your servers. No external SaaS dependency, no data privacy concerns.
- **Query-focused.** Not another broad monitoring tool. QueryLens is purpose-built for database query performance -- EXPLAIN analysis, index recommendations, regression detection, and AI optimization.
- **Production-ready.** Configurable sampling rate, Octane-safe architecture, Laravel Gate authentication, and per-request isolation. Designed for high-traffic applications.
- **Actionable.** Every feature produces a concrete next step -- an index to create, a query to rewrite, a regression to investigate. Not just dashboards.
- **100% free and open-source.** Every feature is available to everyone.

---

How QueryLens Compares
----------------------

[](#how-querylens-compares)

All features included. No paid tiers. MIT licensed. Community-driven.

FeatureQueryLensDebugbarTelescopePulseNightwatchDeploymentSelf-hostedSelf-hostedSelf-hostedSelf-hostedCloudPriceFreeFreeFreeFreeSubscriptionEXPLAIN AnalysisDeep + human-readableNoNoNoNoIndex RecommendationsAutomatedNoNoNoNoRegression DetectionCI-integratedNoNoNoLimitedAI Query OptimizationOpenAI-compatibleNoNoNoNoTransaction TrackingFull lifecycleNoYesNoNoFilament PluginNative panel integrationNoNoNoNoRequest SamplingConfigurable rateNoYesYesN/AAlertingLog, Mail, SlackNoNoNoYesN+1 DetectionAutomaticYesYesNoNoCode Origin TracingFile + line numberYesYesNoNoRequest WaterfallVisual timelineYesNoNoNo---

Features
--------

[](#features)

### Dashboard Overview

[](#dashboard-overview)

Real-time query monitoring dashboard with stats overview, query list, and performance ratings. Supports live polling, search, and filtering by query type, duration, and slow status.

[![Dashboard Overview](docs/images/dashboard.png)](docs/images/dashboard.png)

### EXPLAIN Analysis with Human-Readable Output

[](#explain-analysis-with-human-readable-output)

Run EXPLAIN on any captured query directly from the dashboard. Results are parsed into human-readable descriptions explaining what the database engine is doing -- table scans, index usage, join strategies, and row estimates.

[![EXPLAIN Analysis](docs/images/explain.png)](docs/images/explain.png)

### Index Recommendation Engine

[](#index-recommendation-engine)

Analyzes query patterns over configurable time windows and recommends specific indexes to create. Outputs ready-to-run `CREATE INDEX` statements with impact estimates based on actual query frequency and duration.

### Query Regression Detection and CI Integration

[](#query-regression-detection-and-ci-integration)

Compare query performance between time periods to detect regressions. Integrates with CI/CD pipelines via the `query-lens:check-regression` command. Supports webhook notifications for automated alerting when performance degrades.

[![Regression Detection](docs/images/regression-cli.png)](docs/images/regression-cli.png)

### AI-Powered Query Optimization

[](#ai-powered-query-optimization)

Submit slow queries to any OpenAI-compatible API for optimization suggestions. Returns rewritten SQL, explanation of changes, and estimated performance improvement. Results are cached to avoid redundant API calls.

### Transaction Tracking

[](#transaction-tracking)

Track database transaction lifecycle -- begin, commit, rollback events with duration, nesting depth, and query count. Associates queries with their enclosing transaction for debugging deadlocks and long-running transactions.

### Filament Panel Integration

[](#filament-panel-integration)

Native Filament v3 plugin with real pages, Table Builder, Chart Widgets, and Stats Overview. Register with a single line in your panel configuration. Works alongside the standalone dashboard.

```
use GladeHQ\QueryLens\Filament\QueryLensPlugin;

$panel->plugin(QueryLensPlugin::make());
```

### Request Waterfall Visualization

[](#request-waterfall-visualization)

Visual timeline of all queries within a single HTTP request, showing execution order, duration bars, and overlap detection. Identifies sequential queries that could be parallelized.

[![Request Waterfall](docs/images/waterfall.png)](docs/images/waterfall.png)

### Performance Trend Tracking

[](#performance-trend-tracking)

Track P50, P95, and P99 latency over time with configurable granularity (hourly or daily). Identify slow degradation patterns before they become incidents. Top queries ranked by total impact (frequency multiplied by duration).

[![Performance Trends](docs/images/trends.png)](docs/images/trends.png)

---

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

[](#quick-start)

### 1. Install the package

[](#1-install-the-package)

```
composer require gladehq/laravel-query-lens
```

### 2. Publish configuration and migrations

[](#2-publish-configuration-and-migrations)

```
php artisan vendor:publish --tag=query-lens-config
php artisan vendor:publish --tag=query-lens-migrations
```

### 3. Run migrations

[](#3-run-migrations)

```
php artisan migrate
```

### 4. Enable in your environment

[](#4-enable-in-your-environment)

```
QUERY_LENS_ENABLED=true
```

### 5. Visit the dashboard

[](#5-visit-the-dashboard)

Open `/query-lens` in your browser.

---

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

[](#configuration)

The configuration file is published to `config/query-lens.php`. Key options:

### Storage Driver

[](#storage-driver)

```
'storage' => [
    'driver' => env('QUERY_LENS_STORAGE', 'database'), // 'cache' or 'database'
    'connection' => env('QUERY_LENS_DB_CONNECTION', null),
    'table_prefix' => 'query_lens_',
    'retention_days' => env('QUERY_LENS_RETENTION_DAYS', 365),
],
```

- **cache** -- Ephemeral storage using Laravel's cache. No persistence across restarts. Good for development.
- **database** -- Persistent storage with full query history, aggregation, and trend tracking. Required for production features like regression detection and index recommendations.

### Sampling Rate

[](#sampling-rate)

```
'sampling_rate' => env('QUERY_LENS_SAMPLING_RATE', 1.0),
```

Controls what fraction of requests have their queries recorded. `1.0` records every request. `0.1` records 10%. The decision is made once per request so all queries within a sampled request are captured together.

### Authentication

[](#authentication)

```
'web_ui' => [
    'allowed_ips' => ['127.0.0.1', '::1'],
    'auth_gate' => env('QUERY_LENS_AUTH_GATE', null),
],
```

By default, the dashboard is restricted to localhost. For production, configure a Laravel Gate:

```
// In AuthServiceProvider
Gate::define('viewQueryLens', function ($user) {
    return $user->isAdmin();
});
```

```
QUERY_LENS_AUTH_GATE=viewQueryLens
```

### AI Provider Setup

[](#ai-provider-setup)

```
'ai' => [
    'enabled' => env('QUERY_LENS_AI_ENABLED', false),
    'provider' => env('QUERY_LENS_AI_PROVIDER', 'openai'),
    'api_key' => env('QUERY_LENS_AI_KEY'),
    'model' => env('QUERY_LENS_AI_MODEL', 'gpt-4o-mini'),
    'endpoint' => env('QUERY_LENS_AI_ENDPOINT', 'https://api.openai.com/v1/chat/completions'),
    'cache_ttl' => 3600,
    'rate_limit' => 10,
],
```

Works with any OpenAI-compatible API endpoint. AI features are entirely optional -- the package is fully functional without them.

### Transaction Tracking

[](#transaction-tracking-1)

```
QUERY_LENS_TRACK_TRANSACTIONS=true
```

### Alert Channels

[](#alert-channels)

```
'alerts' => [
    'enabled' => env('QUERY_LENS_ALERTS', false),
    'channels' => ['log', 'mail', 'slack'],
    'slack_webhook' => env('QUERY_LENS_SLACK_WEBHOOK'),
    'mail_to' => env('QUERY_LENS_MAIL_TO'),
    'cooldown_minutes' => 5,
],
```

---

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

[](#artisan-commands)

### `query-lens:aggregate`

[](#query-lensaggregate)

Pre-calculates hourly and daily performance aggregates for trend charts and top query rankings. Schedule this to run hourly in your `app/Console/Kernel.php`:

```
$schedule->command('query-lens:aggregate')->hourly();
```

### `query-lens:prune`

[](#query-lensprune)

Cleans up old query data based on the configured retention period. Schedule daily:

```
$schedule->command('query-lens:prune')->daily();
```

### `query-lens:suggest-indexes`

[](#query-lenssuggest-indexes)

Analyzes recorded query patterns and recommends database indexes:

```
php artisan query-lens:suggest-indexes --days=7
php artisan query-lens:suggest-indexes --sql="SELECT * FROM orders WHERE user_id = ? AND status = ?"
php artisan query-lens:suggest-indexes --format=json
```

### `query-lens:check-regression`

[](#query-lenscheck-regression)

Detects query performance regressions by comparing current period against the previous period. Designed for CI/CD pipelines:

```
php artisan query-lens:check-regression --period=daily --threshold=0.2
php artisan query-lens:check-regression --webhook --format=json
```

Returns exit code `1` when regressions are detected, making it suitable for CI pipeline gates.

---

Filament Integration
--------------------

[](#filament-integration)

QueryLens includes a native Filament v3 plugin. Filament is optional -- the package works without it.

### Register the plugin

[](#register-the-plugin)

```
use GladeHQ\QueryLens\Filament\QueryLensPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        ->plugins([
            QueryLensPlugin::make()
                ->dashboard()    // Query Dashboard page
                ->alerts()       // Alert Management page
                ->trends(),      // Performance Trends page
        ]);
}
```

### Customize

[](#customize)

```
QueryLensPlugin::make()
    ->dashboard(true)
    ->alerts(false)          // Disable alerts page
    ->trends(true)
    ->navigationGroup('Monitoring');
```

The plugin provides:

- **Dashboard** -- Stats overview widget, query table with search/filter/sort, View and Explain actions
- **Alerts** -- CRUD management for alert rules with modal forms
- **Trends** -- Performance and volume chart widgets, top queries table with period selector

---

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

[](#requirements)

- PHP 8.1+
- Laravel 10.x, 11.x, or 12.x
- Filament 3.x (optional, for panel integration)

---

Documentation
-------------

[](#documentation)

Read complete documentation at [Documentation](https://querylens.dulitharajapaksha.com/docs).

---

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

[](#contributing)

Contributions are welcome. Please submit pull requests against the `master` branch. Run the test suite before submitting:

```
./vendor/bin/phpunit
```

---

License
-------

[](#license)

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

---

Credits
-------

[](#credits)

Developed by [Dulitha Rajapaksha](https://github.com/dulithamahishka94) for [GladeHQ](https://profile.dulitharajapaksha.com).

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance76

Regular maintenance activity

Popularity10

Limited adoption so far

Community7

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 ~3 days

Total

3

Last Release

132d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/130d3ca03c3035d1d05d614d5555b3956c254b774bd550bbb80ed35bb99b4ad4?d=identicon)[dulithamahishka94](/maintainers/dulithamahishka94)

---

Top Contributors

[![dulithamahishka94](https://avatars.githubusercontent.com/u/64469682?v=4)](https://github.com/dulithamahishka94 "dulithamahishka94 (55 commits)")

---

Tags

composerdatabaselaravel-frameworkpackagesphp8querieslaravelprofilerdatabaseperformancesqleloquentqueryoptimizationanalyzer

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/gladehq-laravel-query-lens/health.svg)

```
[![Health](https://phpackages.com/badges/gladehq-laravel-query-lens/health.svg)](https://phpackages.com/packages/gladehq-laravel-query-lens)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k51.0M7.6k](/packages/larastan-larastan)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[spatie/laravel-health

Monitor the health of a Laravel application

87411.3M153](/packages/spatie-laravel-health)[itpathsolutions/dbstan

Database Standardization and Analysis Tool for Laravel

442.1k](/packages/itpathsolutions-dbstan)[aedart/athenaeum

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

245.2k](/packages/aedart-athenaeum)[simplestats-io/laravel-client

Analytics for Laravel. Track visitors, registrations, and payments. Discover which channels actually drive revenue, not just traffic. Server-side, GDPR compliant, ad-blocker proof.

5019.3k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

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