PHPackages                             clcbws/laravel-eloquent-insight - 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. clcbws/laravel-eloquent-insight

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

clcbws/laravel-eloquent-insight
===============================

Premium Eloquent performance suite with N+1 resolution, ghost relation detection, hydration profiling, and AST auto-fixing.

v1.0.1(2mo ago)62MITPHPPHP ^8.2

Since May 6Pushed 2mo agoCompare

[ Source](https://github.com/ahtesham-clcbws/laravel-eloquent-insight)[ Packagist](https://packagist.org/packages/clcbws/laravel-eloquent-insight)[ Docs](https://github.com/clcbws/laravel-eloquent-insight)[ RSS](/packages/clcbws-laravel-eloquent-insight/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (6)Versions (3)Used By (0)

Laravel Eloquent Insight 🧠
==========================

[](#laravel-eloquent-insight-)

[![Latest Version on GitHub](https://camo.githubusercontent.com/28ea8db25a43d7cae6108879810e0ba59c34f03ce8fb8812629c712bb199c0ed/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f616874657368616d2d636c636277732f6c61726176656c2d656c6f7175656e742d696e73696768743f696e636c7564655f70726572656c6561736573267374796c653d666c61742d737175617265)](https://github.com/ahtesham-clcbws/laravel-eloquent-insight/releases)[![Total Downloads](https://camo.githubusercontent.com/2438f1964a15c625805a969083b452c6186b8448d3c21dc278efb5e2e1cced3a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636c636277732f6c61726176656c2d656c6f7175656e742d696e73696768742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/clcbws/laravel-eloquent-insight)[![License](https://camo.githubusercontent.com/509d316be6615603cd9f2b8c81772ef2936e31636f3e7b5ba1a61dbbbdcfeaf9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f616874657368616d2d636c636277732f6c61726176656c2d656c6f7175656e742d696e73696768743f7374796c653d666c61742d737175617265)](https://github.com/ahtesham-clcbws/laravel-eloquent-insight/blob/main/LICENSE)

**Laravel Eloquent Insight** is a premium performance suite that identifies, ranks, and resolves database bottlenecks. While most tools just "shout" at you when an N+1 violation happens, Insight provides the **intelligence to understand why** and the **tools to fix it automatically**.

Fully optimized for **Laravel 13.x**, with legacy support for 12.x and 11.x.

---

❓ Why Eloquent Insight?
-----------------------

[](#-why-eloquent-insight)

In standard Laravel development, the **N+1 Problem** is the #1 killer of application performance. You load 50 users, and Laravel accidentally fires 51 queries to fetch their profiles.

**The Problem with Other Tools:**

- 🐢 **Runtime Overhead**: They slow down your production app while "watching" for errors.
- 📣 **Noise**: They give you a flat list of errors without telling you which ones actually hurt your performance.
- 🔧 **Manual Labor**: You still have to manually find the code and fix it.

**The Insight Solution:**

- ⚡ **Zero Production Overhead**: Recording only happens in dev; production uses a static O(1) manifest.
- 🏆 **Impact Scoring**: We tell you which bottlenecks are **CRITICAL** (e.g., 100+ redundant queries) vs. moderate.
- 🧙 **Auto-Refactoring**: Our AST-engine can actually **write the fix into your code** for you.

---

✨ Key Features (The Elite Suite)
--------------------------------

[](#-key-features-the-elite-suite)

### 📊 Impact Scoring

[](#-impact-scoring)

Not all N+1s are equal. Insight ranks every violation:

- 🔴 **CRITICAL**: Generating 50+ redundant queries. Fix immediately!
- 🟠 **HIGH**: Generating 10-50 queries. Significant slowdown.
- 🔵 **MODERATE**: Low-level redundancy.

### 👻 Ghost Relation Detection

[](#-ghost-relation-detection)

Sometimes you use `->with(['user', 'profile'])` but then delete the code that used the profile. The `profile` is still being loaded, wasting memory and DB time. Insight flags these "Ghost Relations" so you can strip them out.

### 💧 Hydration Profiling (The "Fat Model" Finder)

[](#-hydration-profiling-the-fat-model-finder)

If you `SELECT *` on a table with 50 columns but only display the `name`, you are wasting memory. Insight compares what you **fetched** vs. what you **accessed**, suggesting surgical `->select([...])` arrays.

### 🗺️ Query Topology Visualization

[](#️-query-topology-visualization)

Complex apps have messy relationship chains. Insight generates a **Mermaid.js** graph that shows exactly how your queries flow, helping you visualize the "execution distance" between your models.

### 🔄 Redundancy (Duplicate) Detection

[](#-redundancy-duplicate-detection)

Detects identical SQL queries with matching bindings fired in the same request—often a sign of redundant service calls or missing caching logic.

---

🚀 The "Capture-Compile-Resolve" Workflow
----------------------------------------

[](#-the-capture-compile-resolve-workflow)

Insight follows a professional 3-step lifecycle:

1. **CAPTURE (Local)**: While you develop, Insight records violations in the background. You can see them in your terminal or via the **Browser UI Overlay**.
2. **COMPILE (CI/Build)**: Before deploying, you run `php artisan insight:compile`. This takes all your developer "fixes" and squashes them into a high-speed PHP manifest.
3. **RESOLVE (Production)**: In production, our `RuntimeResolver` reads the manifest and "magically" eager-loads the missing relations with **zero database tracing**.

---

📦 Installation
--------------

[](#-installation)

```
composer require clcbws/laravel-eloquent-insight --dev
```

*Note: The resolution engine is production-safe, but the recording tools are strictly for development.*

---

🛠️ Usage (CLI &amp; Terminal)
-----------------------------

[](#️-usage-cli--terminal)

### 3. Clear the Slate

[](#3-clear-the-slate)

If you want to start a fresh audit session, clear the historical logs:

```
php artisan insight:clear
```

### 4. Audit &amp; Fix

[](#4-audit--fix)

Once violations are captured, run the analysis:

```
# List all captured N+1 violations
php artisan insight:list

# Get a high-level efficiency audit (Hydration, Duplicates, Ghost Relations)
php artisan insight:audit

# Automatically fix N+1 violations
php artisan insight:fix --all
```

### 🚀 Production Deployment

[](#-production-deployment)

For maximum performance in production, compile your detected optimizations into a static manifest. This converts dynamic analysis into an O(1) lookup:

```
php artisan insight:compile
```

This will generate `storage/framework/insight/manifest.json`, which is then used by the runtime engine with zero overhead.

### Smart Auto-Fixer (The Wizard)

[](#smart-auto-fixer-the-wizard)

To have Insight automatically refactor your source code to add missing `with()` calls:

```
php artisan insight:fix --all
```

---

### 🖥️ UI Integration (Controllers, Livewire, Blade)

[](#️-ui-integration-controllers-livewire-blade)

#### 🎨 Browser UI Overlay

[](#-browser-ui-overlay)

In your local environment, a premium Shadow-DOM overlay is injected into your HTML responses.

- **Real-time Alerts**: An "Insight" button appears in the bottom-right corner when issues are detected.
- **Visual Breakdown**: View N+1 violations, Ghost relations, and Duplicate queries without leaving your browser.
- **One-Click Fixes**: Apply AST-based source code refactoring directly from the overlay.

#### 🎮 Controller Usage

[](#-controller-usage)

Perfect for building custom admin APIs or JSON health endpoints.

```
use EloquentInsight\Facades\Insight;

public function checkEfficiency()
{
    $solutions = Insight::getLatestSolutions();
    $efficiency = Insight::getEfficiencyReport();

    return response()->json([
        'score' => Insight::getPerformanceScore(),
        'bottlenecks' => $solutions,
        'ghost_relations' => $efficiency['ghost_relations'],
        'duplicates' => Insight::getDuplicateReport(),
    ]);
}
```

#### ⚡ Livewire Integration

[](#-livewire-integration)

Build a real-time "Eloquent Health" indicator for your admin panel.

```
namespace App\Livewire;

use Livewire\Component;
use EloquentInsight\Facades\Insight;

class PerformanceMonitor extends Component
{
    public function render()
    {
        return view('livewire.performance-monitor', [
            'solutions' => Insight::getLatestSolutions(),
            'score' => Insight::getPerformanceScore(),
            'efficiency' => Insight::getEfficiencyReport(),
        ]);
    }
}
```

#### 🍃 Blade Templates

[](#-blade-templates)

Quickly show an alert to administrators if performance regressions are detected in local dev.

```
@if(app()->isLocal() && Insight::getPerformanceScore()
        🧠 Insight Notice: Your database efficiency has dropped to {{ Insight::getPerformanceScore() }}%.
        Run php artisan insight:audit to review.

@endif
```

---

🏗️ Architecture
---------------

[](#️-architecture)

1. **Collector**: Low-level event listeners for Eloquent events.
2. **Heuristic Engine**: Pattern-matching logic to identify entry points.
3. **AST Fixer**: Safe PHP code modification via Abstract Syntax Trees.
4. **O(1) Resolver**: High-speed manifest loader for production.

---

🚀 Roadmap
---------

[](#-roadmap)

Future versions of **Eloquent Insight** will focus on expanding the auto-fix capabilities:

- **Automated Hydration Optimization**: Automatically inject `->select()` calls based on detected attribute access patterns.
- **Duplicate Query Refactoring**: Identify redundant logic blocks and suggest caching or result-reuse strategies.
- **Custom Heuristic Rules**: Allow developers to define their own performance "red lines."
- **In-Browser IDE Links**: Click a violation in the audit report to jump directly to the line in VS Code/PhpStorm.

---

📊 Comparison: Why Insight Wins
------------------------------

[](#-comparison-why-insight-wins)

FeatureStandard Trackers (DebugBar/Clockwork)Laravel Eloquent Insight**Production Overhead**🐢 High (Continuous Tracing)⚡ **Zero** (Static Resolver)**Resolution**📣 Manual Fixing Only🧙 **Auto-Fix (AST Engine)****Analysis**📄 Flat List of Queries🏆 **Impact Scoring (Weighted)****Optimization**❌ None📦 **O(1) Compiled Manifest****Visuals**📊 Generic Tables🗺️ **Mermaid Topology Graphs**---

⚙️ Advanced Configuration
-------------------------

[](#️-advanced-configuration)

Beyond the basic toggles, you can fine-tune the engine in `config/insight.php`:

### `ignore_namespaces`

[](#ignore_namespaces)

Prevent Insight from analyzing internal framework traces. This keeps your reports focused on **your** code.

```
'ignore_namespaces' => [
    'Illuminate\\',
    'EloquentInsight\\',
    'Sentry\\', // Ignore third-party packages
],
```

### `storage_path`

[](#storage_path)

Custom location for the violation buffer and exported reports.

```
'storage_path' => storage_path('framework/insight'),
```

---

🛡️ Production Security &amp; Gating
-----------------------------------

[](#️-production-security--gating)

We take production stability seriously. **Eloquent Insight** uses a dual-layer gate:

1. **Physical Gating**: The `ViolationInterceptor` and `EfficiencyInterceptor` strictly check `\app()->isLocal()` before registering any listeners.
2. **Feature Gating**: All recording logic is disabled if `INSIGHT_ENABLED` is false in your `.env`.

In production, only the **Runtime Resolver** is active, performing a single O(1) array lookup per request. **No traces are generated, and no files are written.**

---

🛠️ Troubleshooting
------------------

[](#️-troubleshooting)

### "The UI Overlay isn't appearing"

[](#the-ui-overlay-isnt-appearing)

1. Ensure `INSIGHT_UI_ENABLED=true` is set in your `.env`.
2. Verify you are in the `local` environment (`APP_ENV=local`).
3. Insight only injects into standard HTML responses (it skips JSON/API calls).

### "Permission denied in storage"

[](#permission-denied-in-storage)

Insight needs to write to `storage/framework/insight/`. Ensure this directory is writable by your web server:

```
mkdir -p storage/framework/insight/reports
chmod -R 775 storage/framework/insight
```

---

🤝 Credits
---------

[](#-credits)

- **Author**: [Ahtesham](mailto:ahtesham@clcbws.com)
- **Company**: [Broadway Web Service](https://www.clcbws.com)

---

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance85

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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

2

Last Release

79d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/17913874?v=4)[Ahtesham Abdul Aziz](/maintainers/ahtesham-clcbws)[@ahtesham-clcbws](https://github.com/ahtesham-clcbws)

---

Top Contributors

[![ahtesham-clcbws](https://avatars.githubusercontent.com/u/17913874?v=4)](https://github.com/ahtesham-clcbws "ahtesham-clcbws (3 commits)")

---

Tags

laraveldatabaseperformanceeloquentAuditinsightquery-optimizationn plus 1clcbws

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/clcbws-laravel-eloquent-insight/health.svg)

```
[![Health](https://phpackages.com/badges/clcbws-laravel-eloquent-insight/health.svg)](https://phpackages.com/packages/clcbws-laravel-eloquent-insight)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M246](/packages/laravel-ai)[itpathsolutions/dbstan

Database Standardization and Analysis Tool for Laravel

463.0k](/packages/itpathsolutions-dbstan)

PHPackages © 2026

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