In modern web applications, handling requests securely and efficiently is critical. Laravel provides a powerful feature called middleware, which acts as a filter between an HTTP request and your application. Middleware can perform actions like authentication, logging, and input validation before the request reaches the controller.
In this blog, we’ll explore what middleware is, why it’s useful, and how to create and use middleware in Laravel applications.
What is Middleware in Laravel?
Middleware is essentially a layer that sits between the request and the response. It inspects, modifies, or rejects incoming requests before they reach your application logic.
For example:
- Redirecting unauthenticated users.
- Ensuring requests contain valid tokens.
- Logging user activities.
- Restricting access based on user roles.
Think of middleware as a security checkpoint for your Laravel app.
Built-in Middleware in Laravel
Laravel comes with several middleware out of the box:
- Authenticate → Ensures a user is logged in.
- EncryptCookies → Encrypts cookies for security.
- VerifyCsrfToken → Protects against CSRF attacks.
- ThrottleRequests → Limits repeated requests (rate limiting).
Creating Custom Middleware
You can create your own middleware using the Artisan command:
This generates a middleware file in app/Http/Middleware/CheckRole.php.
Example: Role-Based Access Middleware
Here’s what happens:
- If the authenticated user doesn’t match the required role, they are redirected.
- Otherwise, the request continues to the next step.
Registering Middleware
Once created, register your middleware in app/Http/Kernel.php.
Global Middleware (applies to all requests)
Add it to the $middleware array.
Route Middleware (applies to specific routes)
Add it to the $routeMiddleware array:
Applying Middleware to Routes
You can assign middleware to specific routes or groups in routes/web.php.
Example: Applying to a Route
Example: Applying to a Route Group
Middleware Parameters
Notice how checkrole:admin passes parameters to middleware. This makes middleware more flexible—you can use the same middleware for multiple roles.
When to Use Middleware
- Authentication & Authorization: Ensure only allowed users can access certain areas.
- Logging & Analytics: Record user activities.
- Security: Verify tokens, block suspicious requests, and apply CSRF protection.
- Rate Limiting: Prevent abuse by limiting repeated requests.
Conclusion
Laravel middleware provides a simple yet powerful way to filter and manage HTTP requests. Whether you’re enforcing authentication, handling security checks, or implementing role-based access, middleware keeps your application organized, secure, and efficient.
By mastering middleware, you gain more control over how requests are handled before they ever reach your application’s core logic.