What are middleware in Laravel?
In Laravel, middleware are a type of filtering mechanism that sits between a request and the application's response. Middleware is primarily used to inspect and modify incoming HTTP requests before they reach the controller, and it can also manipulate the response before it is sent back to the client.
Here are some common uses of middleware in Laravel:
- Authentication: Ensuring that a user is authenticated before they can access specific routes.
- Logging: Logging the details of every request that comes into your application.
- CSRF Protection: Verifying that the request's CSRF token is valid.
- CORS (Cross-Origin Resource Sharing): Controlling which domains are allowed to access your resources.
- Rate Limiting: Restricting the number of requests a client can make to your API.
Example:
Creating a middleware:
php artisan make:middleware CheckAge
This will generate a file in app/Http/Middleware/CheckAge.php
, where you can define logic for filtering requests:
public function handle($request, Closure $next)
{
if ($request->age <= 18) {
return redirect('home');
}
return $next($request);
}
Here, if the age in the request is less than or equal to 18, the user is redirected to the home
page; otherwise, the request is allowed to proceed.
Registering Middleware:
Middleware can be registered globally (applies to all routes) or assigned to specific routes in the app/Http/Kernel.php
file.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.