Performance: Creating middleware
Middleware affects request processing speed and response time by adding extra steps before or after controller actions.
<?php namespace App\Http\Middleware; use Closure; class CheckAuth { public function handle($request, Closure $next) { // Use cached user info or lightweight check if (!$request->user()?->is_active) { return redirect('login'); } return $next($request); } }
<?php namespace App\Http\Middleware; use Closure; class CheckAuth { public function handle($request, Closure $next) { // Heavy database query inside middleware $user = \DB::table('users')->where('id', $request->user()->id)->first(); if (!$user || !$user->is_active) { return redirect('login'); } return $next($request); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy DB query in middleware | 0 (server-side) | 0 | 0 | [X] Bad |
| Lightweight cached check in middleware | 0 (server-side) | 0 | 0 | [OK] Good |
CheckAge in Laravel?php artisan make:middleware Name.public function handle($request, Closure $next) {
if (!auth()->check()) {
return redirect('login');
}
return $next($request);
}!auth()->check().public function handle($request, Closure $next) {
if ($request->user()->role !== 'admin') {
abort(403, 'Unauthorized');
}
}$next($request) to continue the request.$next($request) if the user is admin, causing no response to be returned.blocked=true by aborting with a 403 Forbidden response. Which handle method implementation correctly achieves this?$request->query('blocked') to get the query parameter value as string.Pass the test and this pattern moves unknown