Middleware in Laravel serves as a bridge between a request and the application. It is a powerful tool for handling HTTP requests and performing tasks such as authentication, logging, CORS handling, and more, before reaching the controller or returning a response. This article explores the concept of middleware in Laravel, its usage, and how to implement custom middleware in your application.
What is Middleware?
Middleware is a layer of code that filters HTTP requests entering your application. It acts as an intermediary between the request and the controller, allowing you to inspect and modify requests or responses.
In Laravel, middleware can be used for:
- Authentication: Verifying that a user is authenticated before allowing access to certain routes.
- Authorization: Checking if a user has the necessary permissions to access specific resources.
- Logging: Tracking information like user activity or request details.
- CORS: Handling Cross-Origin Resource Sharing issues for API requests.
- Maintenance mode: Redirecting users during maintenance or downtime.
Built-in Middleware in Laravel
Laravel comes with several built-in middleware that can be used right out of the box. Some commonly used ones include:
- Authenticate: Ensures that the user is authenticated.
- ThrottleRequests: Limits the rate of incoming requests, preventing abuse.
- VerifyCsrfToken: Protects your application from Cross-Site Request Forgery (CSRF) attacks.
- RedirectIfAuthenticated: Redirects users who are already logged in to the home page.
These middleware can be applied globally, to a group of routes, or to individual routes, based on your needs.
How to Create Custom Middleware
Laravel makes it easy to create custom middleware that suits your application’s unique needs. To create a middleware, use the following Artisan command:
php artisan make:middleware CheckAge
This will generate a new file in the app/Http/Middleware
directory. The CheckAge
middleware might look like this:
namespace App\Http\Middleware;
use Closure;
class CheckAge
{
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return response('You must be 18 years or older.', 403);
}
return $next($request);
}
}
In this example, the CheckAge
middleware checks the user’s age before allowing them to proceed with the request. If the user is under 18, they will receive a 403 error.
Registering Middleware
Once the middleware is created, you need to register it in the app/Http/Kernel.php
file. Laravel provides two main places to register middleware:
- Global Middleware: Middleware that runs on every HTTP request.
- Route Middleware: Middleware that runs on specific routes.
To add a custom middleware to a route, add it to the $routeMiddleware
array in Kernel.php
:
protected $routeMiddleware = [
'checkage' => \App\Http\Middleware\CheckAge::class,
];
Now you can apply the checkage
middleware to specific routes in your web.php file:
Route::get('/profile', function () {
// Profile page logic
})->middleware('checkage');
Middleware Groups
Middleware can also be grouped, allowing you to apply multiple middleware to a route at once. For example, Laravel provides a web
group for routes that require session state, CSRF protection, etc. You can define custom groups in the Kernel.php
file:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\CheckAge::class,
],
];
Middleware is a core feature of Laravel that enables you to manage HTTP requests efficiently. Whether you’re handling authentication, logging, or custom business logic, middleware provides a simple and powerful way to structure your request-handling process. Understanding how to use, create, and register middleware will help you build more secure and scalable applications in Laravel.