PHPackages                             mystus/laravel-query-insights - 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. mystus/laravel-query-insights

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

mystus/laravel-query-insights
=============================

Monitor, analyse, and optimise database query performance in Laravel applications with SQL Server support

00PHP

Since Jan 3Pushed 4mo agoCompare

[ Source](https://github.com/mystus/laravel-query-insights)[ Packagist](https://packagist.org/packages/mystus/laravel-query-insights)[ RSS](/packages/mystus-laravel-query-insights/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Query Insights
======================

[](#laravel-query-insights)

[![Latest Version on Packagist](https://camo.githubusercontent.com/8cfa1e5bfe5cdc2f4b9c697db6b6c760a47632a08d690adf61ee02347c8c7c14/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d79737475732f6c61726176656c2d71756572792d696e7369676874732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mystus/laravel-query-insights)[![Total Downloads](https://camo.githubusercontent.com/8ff1e33ddf3350b8dc9c2e88d95944b2415b303e8c5e74393fed3354a8628bbf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d79737475732f6c61726176656c2d71756572792d696e7369676874732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mystus/laravel-query-insights)[![License](https://camo.githubusercontent.com/4a408345945a1b3e15737b36732bc63c03855d61112f0f8f3cf95d3e2e94168c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d79737475732f6c61726176656c2d71756572792d696e7369676874732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mystus/laravel-query-insights)

A Laravel package for monitoring, analysing, and optimising database query performance. Built from 20+ years of experience optimising SQL Server and MySQL databases in production environments.

Features
--------

[](#features)

- 🔍 **Automatic Query Monitoring** - Captures all database queries with execution times
- ⚡ **Slow Query Detection** - Configurable threshold for identifying performance bottlenecks
- 🔄 **N+1 Query Detection** - Automatically identifies potential N+1 query patterns
- 💡 **Actionable Suggestions** - Get specific recommendations for query optimisation
- 🗄️ **SQL Server Support** - Includes SQL Server-specific optimisation hints
- 📊 **Artisan Reporting** - Generate reports from stored query data
- 🎯 **Zero Configuration** - Works out of the box with sensible defaults

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

[](#installation)

```
composer require mystus/laravel-query-insights
```

The package will auto-register its service provider.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

```
php artisan vendor:publish --tag=query-insights-config
```

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

[](#quick-start)

Query Insights starts monitoring automatically. Access the data anywhere in your application:

```
use Mystus\QueryInsights\Facades\QueryInsights;

// Get all recorded queries
$queries = QueryInsights::getQueries();

// Get only slow queries
$slowQueries = QueryInsights::getSlowQueries();

// Get queries with optimisation suggestions
$needsWork = QueryInsights::getQueriesWithSuggestions();

// Get a summary
$summary = QueryInsights::getSummary();
```

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

[](#configuration)

```
// config/query-insights.php

return [
    // Enable/disable monitoring
    'enabled' => env('QUERY_INSIGHTS_ENABLED', true),

    // Queries slower than this (ms) are flagged
    'slow_threshold' => env('QUERY_INSIGHTS_SLOW_THRESHOLD', 100),

    // Log slow queries to your log file
    'log_slow_queries' => env('QUERY_INSIGHTS_LOG_SLOW', true),

    // Store queries for later analysis
    'store_queries' => env('QUERY_INSIGHTS_STORE', false),

    // Days to retain stored data
    'retention_days' => env('QUERY_INSIGHTS_RETENTION_DAYS', 7),

    // Similar queries before N+1 warning
    'n_plus_one_threshold' => env('QUERY_INSIGHTS_N_PLUS_ONE_THRESHOLD', 5),
];
```

What It Detects
---------------

[](#what-it-detects)

### Performance Issues

[](#performance-issues)

IssueSeverityDescription`SELECT *` usageMediumRecommends selecting specific columnsN+1 queriesHighDetects repeated similar queriesLeading wildcard LIKEMedium`LIKE '%term'` prevents index usageSubqueries in WHEREMediumSuggests JOIN alternativesORDER BY without LIMITLowWarns about potential memory issues### SQL Server Specific

[](#sql-server-specific)

IssueSeverityDescriptionImplicit conversionsHighType mismatches that prevent index usageMissing NOLOCK hintsLowSuggests for read-heavy queries### Safety Checks

[](#safety-checks)

IssueSeverityDescriptionUPDATE without WHERECriticalWarns about full-table updatesDELETE without WHERECriticalWarns about full-table deletesUsage Examples
--------------

[](#usage-examples)

### Display in Development

[](#display-in-development)

Add to your `AppServiceProvider` or create a custom middleware:

```
use Mystus\QueryInsights\Facades\QueryInsights;

// In a view composer or at end of request
$summary = QueryInsights::getSummary();

// $summary contains:
// [
//     'total_queries' => 45,
//     'total_time' => 234.56,
//     'average_time' => 5.21,
//     'slow_queries' => 2,
//     'queries_with_suggestions' => 5,
//     'slowest_query' => [...],
// ]
```

### Temporary Monitoring

[](#temporary-monitoring)

```
use Mystus\QueryInsights\Facades\QueryInsights;

// Disable during bulk operations
QueryInsights::disable();

// ... bulk insert operations ...

QueryInsights::enable();
```

### Adjust Threshold Dynamically

[](#adjust-threshold-dynamically)

```
// Be more strict for critical paths
QueryInsights::setSlowThreshold(50);

// Process order...

// Reset for less critical operations
QueryInsights::setSlowThreshold(200);
```

### Generate Reports

[](#generate-reports)

Enable storage in your config or `.env`:

```
QUERY_INSIGHTS_STORE=true
```

Then run reports:

```
# Today's report
php artisan query-insights:report

# Specific date
php artisan query-insights:report --date=2025-01-02

# Only slow queries
php artisan query-insights:report --slow-only

# Only queries with suggestions
php artisan query-insights:report --with-suggestions
```

Testing
-------

[](#testing)

```
composer test
```

Real-World Performance Tips
---------------------------

[](#real-world-performance-tips)

This package was built from experience optimising databases serving 170+ hospitals with millions of records. Here are some hard-won lessons:

1. **Indexes aren't magic** - They help reads but hurt writes. Profile your actual workload.
2. **N+1 is the silent killer** - A page loading 100 products with `$product->category->name` makes 101 queries. Use eager loading.
3. **COUNT(\*) on large tables is expensive** - Consider caching counts or using estimates for UI.
4. **SQL Server parameter sniffing** - First execution plan gets cached. Use `OPTION (RECOMPILE)` for highly variable queries.
5. **Don't trust ORMs blindly** - Always check `->toSql()` or enable query logging during development.

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

[](#contributing)

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

License
-------

[](#license)

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

Credits
-------

[](#credits)

- [Matthew Fritz](https://github.com/mystus)
- Built with lessons learned from healthcare technology systems in South Africa

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance52

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/2883cb4decf839cf721774e257dbc233478fa482d708a2a72ec0f45b274f19c0?d=identicon)[mystus](/maintainers/mystus)

---

Top Contributors

[![mystus](https://avatars.githubusercontent.com/u/3469624?v=4)](https://github.com/mystus "mystus (1 commits)")

### Embed Badge

![Health badge](/badges/mystus-laravel-query-insights/health.svg)

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

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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