intermediate
Step 7 of 15
Middleware
Laravel Framework
Middleware
Middleware provides a mechanism for filtering and modifying HTTP requests entering your application. Think of middleware as layers that a request passes through before reaching your controller (and layers the response passes through on the way out). Laravel uses middleware for authentication, CORS, CSRF protection, rate limiting, and more. You can create custom middleware for logging, role checking, API key validation, or any cross-cutting concern that should apply to multiple routes.
Creating Custom Middleware
<?php
// php artisan make:middleware EnsureIsAdmin
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class EnsureIsAdmin
{
public function handle(Request $request, Closure $next)
{
if (!$request->user() || !$request->user()->isAdmin()) {
abort(403, 'Access denied. Admin only.');
}
return $next($request);
}
}
// Register in bootstrap/app.php (Laravel 11+):
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'admin' => EnsureIsAdmin::class,
]);
})
// Apply to routes
Route::middleware('admin')->group(function () {
Route::get('/admin/dashboard', [AdminController::class, 'index']);
});
// Logging middleware
class RequestLogger
{
public function handle(Request $request, Closure $next)
{
$start = microtime(true);
$response = $next($request);
$duration = round((microtime(true) - $start) * 1000, 2);
logger()->info('Request', [
'method' => $request->method(),
'url' => $request->fullUrl(),
'status' => $response->getStatusCode(),
'duration_ms' => $duration,
'ip' => $request->ip(),
]);
return $response;
}
}
Pro tip: Middleware can act before the request reaches the controller (authentication checks) or after the response is generated (adding headers, logging). Place the logic before $next($request) for "before" middleware and after for "after" middleware.
Key Takeaways
- Middleware filters HTTP requests before they reach controllers and responses before they reach clients.
- Create middleware with
php artisan make:middlewareand register aliases in the application bootstrap. - Apply middleware to routes with
->middleware('name')or route groups. - Built-in middleware handles auth, CSRF, rate limiting, and CORS automatically.
- Middleware executes in order — place critical checks (auth) before business logic middleware.