Middleware provides a convenient way to inspect and filter HTTP requests entering your application. For example, Laravel includes middleware that verifies whether a user is authenticated. If not, the middleware redirects them to the login page. If they are authenticated, the request is allowed to proceed.Beyond authentication, you can write middleware for logging, CSRF protection, rate limiting, and much more. For a practical breakdown of Laravel 13’s CSRF flow, see CSRF protection.
User-defined middleware lives in the app/Http/Middleware directory.
Laravel ships with two default middleware groups: web and api. The web group is automatically applied to routes in routes/web.php, and the api group to routes in routes/api.php.
Middleware can run logic before or after the request is handled:
// Run logic before the requestpublic function handle(Request $request, Closure $next): Response{ // Pre-processing here return $next($request);}
// Run logic after the responsepublic function handle(Request $request, Closure $next): Response{ $response = $next($request); // Post-processing here return $response;}
To apply middleware to specific routes, chain the middleware method on the route definition:
use App\Http\Middleware\EnsureTokenIsValid;Route::get('/profile', function () { // ...})->middleware(EnsureTokenIsValid::class);
Pass an array to apply multiple middleware at once:
Route::get('/', function () { // ...})->middleware([First::class, Second::class]);
To exclude a route from a middleware applied to a group, use withoutMiddleware:
use App\Http\Middleware\EnsureTokenIsValid;Route::middleware([EnsureTokenIsValid::class])->group(function () { Route::get('/', function () { // Middleware applies here }); Route::get('/profile', function () { // Middleware excluded for this route })->withoutMiddleware([EnsureTokenIsValid::class]);});
<?phpnamespace App\Http\Middleware;use Closure;use Illuminate\Http\Request;use Symfony\Component\HttpFoundation\Response;class RedirectIfNotAuthenticated{ public function handle(Request $request, Closure $next): Response { if (! $request->user()) { return redirect('/login'); } return $next($request); }}
Apply it to a route:
Route::get('/dashboard', function () { return view('dashboard');})->middleware(RedirectIfNotAuthenticated::class);
Laravel ships with an auth middleware that handles this pattern already. Before writing your own, check whether the built-in middleware meets your needs.