Laravel Middleware vs FormRequest vs Policy vs Resource: The 5-Layer Security Model (Laravel 13)
One of the fastest ways a Laravel API turns into a security headache is putting auth checks, validation, ownership rules, and JSON shaping inside controllers. Here is the clean 5-layer mental model I use in production L
One of the fastest ways a Laravel API turns into a security headache is putting auth checks, validation, ownership rules, and JSON shaping inside controllers.
Here is the clean 5-layer mental model I use in production Laravel 13 APIs β think of it like airport security:
| Layer | Responsibility | Failure Status |
|---|---|---|
| Middleware | Who are you? (JWT, verified email, JSON & security headers) |
401 / 403 / 429
|
| FormRequest |
What did you bring? (sanitize, validate, prohibited fields) |
422 / 403
|
| Policy | Is this specific record yours? (ownership & RBAC) |
404 / 403
|
| Service |
Keep it atomic. (DB::transaction() + file cleanup) |
Domain Exception |
| API Resource | What leaves the server? (explicit JSON allowlist) | β |
One Pattern That Catches Most Devs Off Guard: Return 404, Not 403
When User B hits GET /api/documents/42 (owned by User A), returning 403 Forbidden confirms Document #42 exists β an IDOR enumeration leak.
Instead, combine a user-scoped query (404) with a Policy fallback (403):
// Layer 1 (Service): Scoped lookup β returns 404 if not owned
$document = $user->documents()->findOrFail($id);
// Layer 2 (Controller): Explicit Policy check as a 403 safety net
$this->authorize('update', $document);
Read the Full Production Walkthrough
In the full guide on my blog, I break down the complete working Laravel 13 code for all 5 layers:
- Wiring
ForceJsonResponse&SecurityHeadersinbootstrap/app.php(noKernel.php) -
FormRequest::authorize()withDocument::class& RBACprohibitedfields - Preventing orphan files with
DB::transaction()on create & delete - Centralized PHP 8
match (true)JSON exception mapping inwithExceptions() - 6 common Laravel API security anti-patterns to avoid
π Read the full guide here: Laravel Middleware vs FormRequest vs Policy vs Resource (Laravel 13)
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.