Laravel

Lesson 03

Middleware and auth boundaries

Attach authentication, rate limits, and request guards at the route boundary instead of hiding them inside actions.

Good Code

routes/api.php
<?php

use App\Http\Controllers\ReviewController;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth:sanctum', 'throttle:reviews'])
    ->prefix('reviews')
    ->group(function () {
        // Middleware makes authentication and rate limits visible at the route boundary.
        Route::post('/', [ReviewController::class, 'store']);
        Route::delete('/{review}', [ReviewController::class, 'destroy']);
    });

Bad Code

app/Http/Controllers/ReviewController.php
<?php

public function destroy(Request $request, Review $review)
{
    // Auth parsing inside the action hides which routes are protected.
    if ($request->bearerToken() !== config('services.admin_token')) {
        abort(401);
    }

    $review->delete();

    return response()->noContent();
}

Review Notes

What to review

Good Code

The good version makes the security story visible before reading controller code. Reviewers can see which routes require an authenticated user and which rate limiter applies.

Bad Code

The bad version hides authentication details in the action body. That makes route audits and behavior reuse fragile.

Takeaways

  • Access and request-wide rules should be visible where the route is declared so protected endpoints are easy to audit.