1. Middleware vs FormRequest vs Policy vs Resource (At a Glance)

Every senior Laravel code review and backend interview eventually hits the same question: "Why split checks across Middleware, FormRequest, Policy, and Resource when you could write them all in the controller?"

The answer is Defense in Depth and Separation of Concerns. Think of an API request like boarding a flight at an airport:

  1. Main Gate Security (Middleware): "Who are you? Do you have a valid passport and visa?" — Validates your JWT token, email verification status, and forces JSON headers before your payload ever touches the controller.
  2. Luggage Scanner (FormRequest): "What is inside your bag? Is the weight and file type allowed?" — Sanitizes fields, enforces MIME types and upload size limits, and rejects bad input with 422 before touching the database.
  3. Seat Boarding Check (Policy): "Everything checks out, but is seat 12B actually yours?" — Verifies object-level ownership ($document->user_id === $user->id) so users can never view, edit, or delete someone else's data.
  4. Packaging & Customs Exit (Resource): "What is allowed to leave the terminal?" — Whitelists safe fields and strips internal database columns, foreign keys, and encrypted secrets.
Layer Directory Primary Question Failure Status
Middleware app/Http/Middleware Is this user authenticated, verified, and within rate limits? 401 / 403 / 429
FormRequest app/Http/Requests Is the incoming payload valid, sanitized, and permitted? 422 / 403
Policy app/Policies Does this user own or have permission on this specific model? 404 / 403
Service app/Services How do DB writes, files, and external APIs stay atomic? Domain Exception
API Resource app/Http/Resources Which exact JSON fields should be exposed to the client? —

2. The Full Laravel 13 Request Lifecycle

When a client sends a request like PUT /api/documents/42 in a modern Laravel 13 SaaS API, it travels through a strict one-way dependency chain: Route → Middleware → FormRequest → Controller → Policy → Service → Model → Resource.

Request Lifecycle Pipeline text
PUT /api/documents/42
  │
  ├─ 1. bootstrap/app.php & AppServiceProvider (routes, rate limiters, policies)
  ├─ 2. Global + API Middleware
  │      ├─ ForceJsonResponse (Before: sets Accept: application/json)
  │      └─ auth:api + verified.email (JWT + email_verified_at check)
  ├─ 3. FormRequest (UpdateDocumentRequest)
  │      ├─ prepareForValidation() → trim / lowercase
  │      ├─ authorize()            → request-level guard
  │      └─ rules()                → 422 on invalid fields
  ├─ 4. Controller (≤ 15 lines — orchestration only)
  │      ├─ $document = $documents->findForUser($user, $id) → 404 if not owned
  │      ├─ $this->authorize('update', $document)           → Policy fallback (403)
  │      ├─ $document = $documents->update($document, $request->validated())
  │      └─ ApiResponse::success(new DocumentResource($document))
  ├─ 5. Global Exit Middleware
  │      └─ SecurityHeaders (After: nosniff, DENY, Referrer-Policy)
  └─ 6. Centralized Exception Handler (withExceptions → strict JSON envelope)

Notice the golden rule: Controllers never run Eloquent queries, touch files, or call third-party APIs. Services never read request() or return HTTP responses — they throw domain exceptions that bootstrap/app.php translates into clean JSON. (If you want a deeper dive into thin controllers, see my MVCS Architecture in Laravel guide.)

3. Layer 1 — Middleware in bootstrap/app.php (No Kernel.php)

Since Laravel 11 (and continuing in Laravel 13), app/Http/Kernel.php and app/Exceptions/Handler.php are no longer part of the application skeleton. Everything is wired cleanly inside bootstrap/app.php:

bootstrap/app.php php
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // After-middleware: attaches security headers to every response
        $middleware->append(SecurityHeaders::class);

        // Before-middleware: forces JSON even if the client forgets Accept header
        $middleware->api(prepend: [
            ForceJsonResponse::class,
        ]);

        $middleware->alias([
            'verified.email' => EnsureEmailVerified::class,
        ]);
    })
    ->withExceptions(/* ... */)
    ->create();

Before Middleware vs After Middleware

Prepending ForceJsonResponse runs before the controller so that a missing Accept: application/json header never causes Laravel to redirect an unauthenticated API request to an HTML /login page:

app/Http/Middleware/ForceJsonResponse.php php
public function handle(Request $request, Closure $next): Response
{
    $request->headers->set('Accept', 'application/json');

    return $next($request);
}

Appending SecurityHeaders runs after the response is built, protecting every web and API endpoint against three classic browser attacks:

app/Http/Middleware/SecurityHeaders.php php
public function handle(Request $request, Closure $next): Response
{
    $response = $next($request);

    $response->headers->set('X-Content-Type-Options', 'nosniff');
    $response->headers->set('X-Frame-Options', 'DENY');
    $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');

    return $response;
}
  • X-Frame-Options: DENY — Blocks clickjacking by forbidding attackers from embedding your app inside an invisible <iframe>.
  • X-Content-Type-Options: nosniff — Stops browsers from MIME-sniffing uploaded images or text files as executable JavaScript (preventing stored XSS via disguised uploads).
  • Referrer-Policy: strict-origin-when-cross-origin — Strips paths and query strings (like /verify-email?token=secret...) when a user clicks an external link, sending only the bare origin so tokens never leak into third-party server logs.

4. Layer 2 — FormRequest (Input Guard & RBAC Field Protection)

A FormRequest runs before your controller method executes and handles three distinct jobs in order: prepareForValidation() (sanitization), authorize() (request permission), and rules() (field validation).

app/Http/Requests/Document/StoreDocumentRequest.php php
class StoreDocumentRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create', Document::class) ?? false;
    }

    public function rules(): array
    {
        return [
            'file'     => ['required', 'file', 'mimes:'.implode(',', config('documents.mimes')), 'max:'.config('documents.max_kb')],
            'title'    => ['required', 'string', 'max:120'],
            'category' => ['required', 'string', 'max:80'],
            'notes'    => ['nullable', 'string', 'max:2000'],
        ];
    }
}

Why Document::class Instead of a $document Object?

During a POST request, no Document row exists in the database yet. Calling $this->user()->can('create', Document::class) asks Laravel's central Gate to look up the policy registered for Document::class in AppServiceProvider and call DocumentPolicy::create(User $user).

Always Use $request->validated(), Never $request->all()

Passing $request->all() to a model or service is how mass-assignment vulnerabilities happen. If an attacker injects is_admin: true or user_id: 1 into a JSON body, $request->validated() strips every key that wasn't explicitly declared in rules().

Handling Admin-Only Fields cleanly

When regular users and admins edit the same model, you have two clean patterns:

  • Conditional prohibited rules: Allow is_featured or status when $this->user()?->hasRole('admin'), and set them to ['prohibited'] for regular users so tampering triggers an explicit 422.
  • Dedicated Admin Endpoints (Enterprise approach): Split into /api/v1/documents/{id} (UpdateDocumentRequest) and /api/v1/admin/documents/{id} (AdminUpdateDocumentRequest behind role:admin middleware). Zero if/else branching inside validation rules.

5. Layer 3 — Policy & Two-Layer Ownership (Why 404 Beats 403)

Suppose User A owns Document #42, and User B sends GET /api/documents/42 or DELETE /api/documents/42. Most tutorials fetch Document::findOrFail(42) and let the Policy throw a 403 Forbidden.

The security problem with 403: Returning 403 Forbidden tells an attacker, "Document #42 definitely exists in this database — it just belongs to someone else." That enables IDOR resource enumeration.

Instead, use two-layer ownership defense:

Two-Layer Ownership Check php
// Layer 1 (DocumentService): Scope the query to the authenticated user → 404 if not owned
public function findForUser(User $user, int $id): Document
{
    return $user->documents()->findOrFail($id);
}

// Layer 2 (DocumentController): Explicit Policy check as a 403 safety net
public function update(UpdateDocumentRequest $request, int $id, DocumentService $documents): JsonResponse
{
    $document = $documents->findForUser($request->user(), $id);
    $this->authorize('update', $document);

    $document = $documents->update($document, $request->validated());

    return ApiResponse::success(new DocumentResource($document), 'Document updated.');
}

If User B requests Document #42, Layer 1 throws ModelNotFoundException → 404 Resource not found, leaking zero information. If a future developer accidentally swaps in an unscoped Document::find($id), Layer 2 (DocumentPolicy) still blocks the breach with 403.

Combining Spatie RBAC with Policies

Keep your controllers and FormRequests completely unaware of Spatie permissions by wrapping role/permission checks inside the Policy itself:

app/Policies/DocumentPolicy.php php
class DocumentPolicy
{
    public function before(User $user, string $ability): ?bool
    {
        return $user->hasRole('admin') ? true : null;
    }

    public function update(User $user, Document $document): bool
    {
        return $document->user_id === $user->id;
    }

    public function delete(User $user, Document $document): bool
    {
        return $document->user_id === $user->id;
    }
}

6. Layer 4 — Service Layer & DB::transaction() File Safety

Combining file uploads with database writes is a classic source of production corruption. Without careful ordering, you either leak orphan files on disk or leave broken download links in MySQL.

On Create: Roll Back the File if the DB Fails

app/Services/DocumentService.php (create) php
$stored = $this->storage->store($file); // Saves with UUID filename

try {
    $document = DB::transaction(function () use ($user, $data, $stored): Document {
        return $user->documents()->create([
            'title'         => $data['title'],
            'category'      => $data['category'],
            'notes'         => $data['notes'] ?? null,
            'file_path'     => $stored['path'],
            'original_name' => $stored['original_name'],
        ]);
    });
} catch (Throwable $e) {
    // Prevent orphan files on disk if the database insert fails
    $this->storage->delete($stored['path']);
    throw $e;
}

On Delete: Commit the DB Delete Before Deleting the File

app/Services/DocumentService.php (delete) php
$path = $document->file_path;

DB::transaction(fn () => $document->delete());

// Only remove from disk once the DB commit succeeds
$this->storage->delete($path);

If you deleted the file first and the database transaction rolled back, the database record would survive while the file was permanently gone — leaving broken attachments across your UI. Committing the DB delete first eliminates that failure mode.

7. Layer 5 — API Resources & Centralized match (true) Exceptions

Never return a raw Eloquent model (return response()->json($user)). Even with $hidden or Laravel 13's #[Hidden] attribute, raw models couple your public API contract directly to your database columns. An API Resource acts as an explicit allowlist:

app/Http/Resources/UserResource.php php
public function toArray(Request $request): array
{
    return [
        'id'                 => $this->id,
        'name'               => $this->name,
        'email'              => $this->email,
        'email_verified_at'  => $this->email_verified_at?->toIso8601String(),
        'two_factor_enabled' => $this->two_factor_confirmed_at !== null,
        'created_at'         => $this->created_at?->toIso8601String(),
    ];
}

Centralized JSON Exception Mapping with PHP 8 match (true)

Instead of scattering try/catch blocks across every controller, let services throw clear domain exceptions and map every /api/* error once inside bootstrap/app.php:

bootstrap/app.php (withExceptions) php
->withExceptions(function (Exceptions $exceptions): void {
    $exceptions->shouldRenderJsonWhen(
        fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
    );

    $exceptions->render(function (Throwable $e, Request $request) {
        if (! $request->is('api/*')) {
            return null;
        }

        return match (true) {
            $e instanceof EmailNotVerifiedException => ApiResponse::error($e->getMessage(), [], 403),
            $e instanceof TwoFactorRequiredException => ApiResponse::error($e->getMessage(), [], 401, ['two_factor_required' => true]),
            $e instanceof ValidationException       => ApiResponse::error($e->getMessage(), $e->errors(), 422),
            $e instanceof AuthenticationException   => ApiResponse::error('Unauthenticated.', [], 401),
            $e instanceof ThrottleRequestsException => ApiResponse::error('Too many attempts.', [], 429),
            $e instanceof NotFoundHttpException     => ApiResponse::error('Resource not found.', [], 404),
            $e instanceof HttpExceptionInterface    => ApiResponse::error($e->getMessage() ?: 'Request failed.', [], $e->getStatusCode()),
            default                                 => ApiResponse::error('Server error.', [], 500),
        };
    });
})

Why match (true) works so well here: it evaluates each instanceof branch top-to-bottom with strict semantics, requires no break statements, returns directly as an expression, and guarantees that an unhandled database crash returns a safe generic 500 Server error. instead of leaking SQL queries or server paths.

8. Common Anti-Patterns to Avoid

  1. Returning 403 on unscoped lookups: Always scope by $user->relation()->findOrFail($id) first so attackers cannot enumerate IDs.
  2. Using $request->all() instead of $request->validated(): Opens mass-assignment holes the moment a new column is added to $fillable.
  3. Putting request() or response() inside Services: Makes your service impossible to reuse in Artisan commands, jobs, or unit tests.
  4. Skipping ForceJsonResponse on API routes: One missing Accept header turns a 401 JSON error into a broken HTML redirect.
  5. Deleting files before DB commit: Always delete from disk after DB::transaction() succeeds.
  6. Putting generic exception interfaces above specific ones in match (true): Always list specific exceptions (NotFoundHttpException) before parent interfaces (HttpExceptionInterface).

If you are pairing this architecture with API authentication, see Laravel Sanctum vs JWT: Which Should You Use? and Laravel REST API Best Practices. Need a production security audit or custom Laravel backend built with these exact standards? Check out my Laravel Engineering & Architecture Services.

9. Frequently Asked Questions

What is the difference between Middleware, FormRequest, Policy, and Resource in Laravel?+

Middleware enforces authentication, email verification, rate limits, and HTTP headers at the boundary. FormRequest sanitizes and validates incoming payloads before the controller runs. Policy checks resource-level ownership and permissions. API Resource whitelists outgoing JSON fields so internal schema details never leak.

Should Laravel APIs return 404 or 403 for another user's resource?+

Return 404 by scoping queries through the authenticated user's relationship ($user->documents()->findOrFail($id)). Returning 403 leaks that the record ID exists (IDOR enumeration). Keep a Policy check as a secondary fallback.

Where do middleware and exception handlers live in Laravel 13 without Kernel.php?+

In bootstrap/app.php. Use ->withMiddleware() to append global middleware, prepend API middleware, or register aliases, and ->withExceptions() to render consistent JSON error envelopes.

Why pass Document::class instead of a model instance to FormRequest::authorize()?+

On a POST create endpoint, no model row exists yet. Passing the class string tells Laravel's Gate to resolve DocumentPolicy and call its create(User $user) method.

How do you avoid orphan files when a Laravel DB transaction fails?+

Store the uploaded file with a UUID filename, wrap the DB insert in DB::transaction() inside a try/catch, and delete the file inside the catch block if the transaction throws. On delete, commit the DB deletion first, then remove the file from disk.

Work with me

Building a production Laravel API or multi-tenant SaaS?

I architect and ship clean, secure Laravel backends — layered authorization, zero-leak APIs, database tuning, and automated Pest test suites.