# Laravel Excellence Prover MCP

> Laravel Excellence Prover forces your AI agent to write code that meets senior developer standards. It checks for common performance traps like N+1 queries and architectural mistakes, ensuring every line follows Laravel's best practices. This MCP validates everything from mass assignment safety to complex business logic separation.

## Overview
- **Category:** productivity
- **Price:** Free
- **Tags:** laravel, php, code-quality, n-plus-one, structured-reasoning, decision-pivots, eloquent, agentic-pipeline

## Description

You know the drill. You ask your agent to generate a new feature endpoint, and it spits out code that technically runs but you instantly know is garbage. It’s bloated controllers, manual database calls where Eloquent should be used, or worse—N+1 query disasters waiting for high traffic. This MCP forces excellence. It doesn't just check syntax; it audits the entire architecture against proven Laravel idioms. You get code that separates HTTP handling from business logic, uses explicit field whitelisting, and handles transactions correctly. By connecting this MCP through Vinkius, your AI agent gets immediate feedback on every pattern violation—forcing it to fix lazy-loading relationships, properly use FormRequests for validation, or refactor a fat controller into services. The result is reliable code you can actually ship.

## Tools

### validate_laravel_excellence
This single tool validates if the generated Laravel code adheres to best practices across six areas: preventing workarounds, separating responsibilities, securing mass assignment, optimizing queries, and respecting core architecture.

## Prompt Examples

**Prompt:** 
```
I need to list all orders with their products for an admin dashboard. I'll use Order::all() and then loop through to get products in the Blade view.
```

**Response:** 
```
Verdict: N_PLUS_ONE_DETECTED. Order::all() loads orders without products. Each $order->products in Blade fires a separate query. 100 orders = 101 queries. Fix: Order::with('products')->paginate(25). Enable Model::preventLazyLoading() in AppServiceProvider to catch this at dev time. Use withCount('products') if you only need the count.
```

**Prompt:** 
```
POST /api/orders: StoreOrderRequest validates input. CreateOrderAction receives DTO, wraps Order + OrderItems in DB::transaction(), returns Order. Order model has $fillable = ['user_id', 'total', 'status']. Queries: Order::with('items.product') for response. Event: OrderCreated dispatched after commit via $afterCommit. Response via OrderResource.
```

**Response:** 
```
Verdict: CODE_PROVEN. Queries optimized (with('items.product')). No workarounds — FormRequest, Action, DB::transaction(), API Resource, Event. Responsibilities separated (Controller→FormRequest→Action→Model→Event). Mass assignment guarded ($fillable explicit). Architecture solid ($afterCommit, typed DTO, Resource). Ship it.
```

**Prompt:** 
```
I'll validate in the controller with $request->validate(), use $request->all() to create the user, check authorization with an if-statement, and send the welcome email inline after User::create().
```

**Response:** 
```
Verdict: FAT_CONTROLLER. Four violations in one method. (1) Validation belongs in a StoreUserRequest FormRequest, not inline. (2) $request->all() is a mass assignment vulnerability — use $request->validated(). (3) Authorization belongs in a Policy, not an if-statement. (4) Email is a side effect — dispatch UserCreated event, handle email in a Listener. Extract ALL of this from the controller.
```

## Capabilities

### Identify database performance traps
It flags N+1 query patterns, forcing the agent to implement eager loading and proper scopes.

### Enforce architectural separation
The MCP ensures business logic lives outside of controllers, keeping HTTP concerns separate from execution steps.

### Guard against data vulnerabilities
It validates that the agent uses explicit whitelisting for database writes, preventing mass assignment attacks.

### Validate framework idiomatic usage
It rejects manual workarounds and forces the use of built-in Laravel features like Policies or API Resources.

### Ensure transactional integrity
The system verifies that multi-step database writes are wrapped in transactions to prevent partial failures.

## Use Cases

### Building an Admin Dashboard List
You need to list 500 user records and their associated posts. If your agent uses simple `User::all()` in the view loop, it's a disaster. Running this MCP forces the use of `User::with('posts')->paginate(25)`, keeping query count low and performance high.

### Creating a Complex Order Flow
A new user checkout requires updating inventory, creating an order record, and dispatching a payment event. The MCP ensures this whole sequence is wrapped in `DB::transaction()` so if the email fails, the database rollbacks completely.

### Handling User Profile Updates
Instead of letting your agent pass `$request->all()` to create a user model, you run this MCP. It forces the use of FormRequests and explicit whitelisting, guaranteeing only intended fields can be updated.

### Refactoring an Old API Endpoint
An existing controller handles validation, business logic (calculating pricing), and database saving all in one method. The MCP forces you to split that into a dedicated Service class for the calculation and keeping only HTTP handling in the controller.

## Benefits

- Stop hitting the database with N+1 queries. The tool checks for lazy loading in loops and views, forcing the use of `with()` or scopes so your application stays fast under load.
- Never deal with fat controllers again. It mandates that business logic moves out of the controller and into dedicated Service or Action classes, keeping HTTP handling clean and thin.
- Eliminate mass assignment holes. The MCP requires explicit `$fillable` arrays and validates input using `request->validated()`, stopping attackers from injecting random fields like `is_admin=true`.
- Use Laravel the right way. It rejects manual workarounds, forcing your agent to use built-in features like FormRequests for validation or API Resources for structured JSON output.
- Build resilient systems. The tool verifies that multi-model database writes are wrapped in a `DB::transaction()` block, preventing partial failures when things go wrong.

## How It Works

The bottom line is that your agent gets instant feedback on code quality, forcing it to write production-ready, battle-tested Laravel architecture.

1. Give your agent the code snippet or feature description you want it to review.
2. The MCP runs multiple decision pivots, checking for every violation—from query structure to responsibility separation.
3. You receive a structured verdict detailing exactly which best practice was missed and how to fix it using core Laravel features.

## Frequently Asked Questions

**Does Laravel Excellence Prover generate or write Laravel code?**
No. The agent writes the code. The tool VALIDATES that the code meets senior-level Laravel standards — query optimization, framework idioms, responsibility separation, mass assignment protection, and architectural compliance. It catches the five failure modes before the code is committed.

**What does it catch that a system prompt instruction doesn't?**
Prompt instructions are suggestions — agents routinely ignore 'use eager loading' or 'validate with FormRequests.' Tool calls are obligations — the agent must fill every field. The engine has 22 consistency rules that catch specific anti-patterns: N+1, raw SQL without justification, env() in app code, unbounded get()/all(), synchronous heavy I/O, dd()/dump() in production, magic values, vague claims like 'follows best practices', and platitude conclusions. A prompt cannot enforce these — a tool schema can.

**Why is N+1 checked before everything else?**
Because N+1 is the single most common and damaging performance anti-pattern in Laravel. A beautifully architected application with clean controllers and perfect FormRequests will still crash under load if every Blade view triggers 100 lazy-loaded queries. N+1 is checked first because no amount of clean architecture compensates for a database under siege.

**Can I use this for existing legacy Laravel codebases?**
Yes. When refactoring legacy code, call the tool to validate each change against excellence standards. The tool catches the same patterns regardless of whether you're writing new code or improving old code. Start with the most critical pivot: enable Model::preventLazyLoading() to surface all N+1 issues, then progressively extract logic from fat controllers into Services, add FormRequests, and define $fillable.

**How does the `validate_laravel_excellence` tool check for proper authorization?**
It enforces that authorization logic lives in dedicated Policies and Middleware. The Prover rejects code where checks are implemented using inline 'if' statements or manual guards within a controller method, forcing separation of concerns.

**Does Laravel Excellence Prover handle multi-model data integrity?**
Yes, it verifies that any sequence of database writes affecting multiple models uses `DB::transaction()`. This guarantees atomicity, preventing partial failures if one step in the process fails.

**How does the tool ensure clean input handling when processing form data?**
The Prover mandates using FormRequests for all incoming data. It forces you to rely on `$request->validated()` instead of passing raw data via `$request->all()`, eliminating mass assignment risks at the source.

**What happens if I try to use a non-idiomatic pattern?**
The tool is designed to flag any deviation from Laravel's intended patterns, such as using manual validation arrays instead of FormRequests, or calling `env()` in application code rather than `config()`. It demands the framework's built solution.