Middleware sits between an incoming request and your application, acting as a filter that can inspect, modify, or reject a request before it reaches a controller (or modify the response on the way out). Common built-in examples include auth, throttle, and verified.
Generate a custom middleware with:
php artisan make:middleware EnsureUserIsSubscribed
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class EnsureUserIsSubscribed
{
public function handle(Request $request, Closure $next)
{
if (! $request->user()?->subscribed()) {
return redirect('/subscribe');
}
return $next($request);
}
}
Since Laravel 11, middleware is registered centrally in bootstrap/app.php rather than a Kernel.php file:
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'subscribed' => \App\Http\Middleware\EnsureUserIsSubscribed::class,
]);
})
Apply it to a route with ->middleware('subscribed'), or to a whole group as shown in the routing chapter. Middleware can run before the request (validation, auth checks) or after it (modifying the response, logging), depending on where $next($request) is called relative to your logic.