Laravel Middleware: Advanced Patterns
Laravel Middleware: Advanced Patterns
Laravel Middleware: Advanced Patterns
Tip: Middleware Groups
$middleware->group('web', [
EncryptCookies::class,
StartSession::class,
]);
Apply multiple middleware at once with middleware('web').
Gotcha: Middleware Priority
$middleware->priority([
Authenticate::class,
Authorize::class,
]);
Priority determines execution order when multiple middleware are applied.
Tip: Conditional Middleware
public function handle(Request $request, Closure $next): Response
{
if (! $this->shouldApply($request)) {
return $next($request);
}
}
Gotcha: Middleware Runs Before Controller
If your middleware redirects, the controller never executes.
Tip: Terminable Middleware
public function terminate(Request $request, Response $response): void
{
Log::info('Request completed', [
'duration' => microtime(true) - LARAVEL_START,
]);
}
Gotcha: Middleware Singleton
Register middleware as a singleton if you need the same instance for handle() and terminate().
Tip: Use route:cache Carefully
php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.
Tip: Model APP_KEY Rotation
Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.
Gotcha: Local Scope Leaks
Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.
Senior Insight
The Laravel ecosystem moves fast, and keeping up with every new first-party package can feel overwhelming. I've found that mastering the core — the container, Eloquent, queues, and the HTTP layer — pays far more dividends than chasing every new release. Architecture and debugging skills transcend framework versions. When I mentor developers, I focus on understanding the 'why' behind Laravel's design choices rather than memorizing syntax. The framework changes; the principles don't.
Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)