Middleware provides a mechanism for filtering and inspecting HTTP requests entering a Laravel application. Middleware runs before (and optionally after) a request reaches its intended route or controller, making it a common place to handle concerns like authentication, logging, and CORS.
Each piece of middleware receives the incoming request and a $next closure representing the next layer of the application. Middleware can inspect or modify the request, pass it deeper into the application by calling $next($request), or reject it early by returning a response directly.
public function handle(Request $request, Closure $next)
{
if (!$request->user()) {
return redirect('login');
}
return $next($request);
}
Middleware can be applied globally to every HTTP request, assigned to specific routes or route groups, or attached to controllers. Named middleware assigned to routes is typically referenced by an alias rather than its full class name.
Route::get('/dashboard', function () {
// ...
})->middleware('auth');
Laravel ships with several middleware classes out of the box, including ones that verify a user is authenticated, verify CSRF tokens on state-changing requests, and trim whitespace from incoming request input.
By: Tomas Silny
Edited: 2026-08-13 03:31:19