Laravel Middleware Explained: A Complete Guide for Beginners
Laravel Middleware is a mechanism used to filter HTTP requests entering your Laravel application. It allows you to inspect, modify, or reject a request before it reaches your application’s controller.
Middleware is commonly used for authentication, authorization, logging, CORS, rate limiting, and request validation.
How Does Laravel Middleware Work?
When a user sends a request, Laravel processes it through the middleware before executing the controller.
Request -> Middleware -> Controller -> Response
For example, you may want only logged-in users to access a particular page. The auth middleware can check whether the user is authenticated before allowing the request to continue.
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware('auth');
If the user is not authenticated, Laravel can redirect them to the login page.
Creating Custom Middleware
You can create your own middleware using Artisan:
php artisan make:middleware CheckUserRole
Laravel creates a middleware class where you can define your request-checking logic.
public function handle($request, Closure $next) {
if ($request->user() && $request->user()->is_admin) {
return $next($request);
}
abort(403);
}
Here, the middleware allows the request to continue only if the user is an administrator.
Applying Middleware
Middleware can generally be applied to:
- Routes – Protect specific routes.
- Route groups – Apply middleware to multiple routes.
- Controllers – Apply middleware to controller actions.
- Global requests – Run middleware for incoming requests across the application.
For example:
Route::middleware(['auth'])->group(function () {
Route::get('/profile', [ProfileController::class, 'index']);
Route::get('/settings', [SettingsController::class, 'index']);
});
Why Use Middleware?
Middleware helps keep application logic organized. Instead of putting authentication or permission checks inside every controller, you can handle these checks in one reusable layer.
Common use cases include:
- User authentication
- Role and permission checks
- API rate limiting
- Request logging
- IP filtering
- CORS handling
- Request modification
Conclusion
Laravel Middleware provides a clean and reusable way to control how requests are processed. By separating request filtering from your controllers, middleware makes Laravel applications easier to secure, maintain, and scale.
If you’re building a Laravel application, understanding middleware is essential because it plays an important role in authentication, security, and request handling.
