Middleware in Laravel
What is Middleware in Laravel?
Middleware in Laravel works as a filter for HTTP requests that enter your application. It enables you to analyze, modify, and reject requests before they reach your routes or controllers.
Origin
Middleware is a basic idea in Laravel, inspired by comparable patterns in other frameworks, and provides a flexible manner of handling request lifecycle logic.
Why is Middleware Used?
- Enhanced Security: Used for authentication, authorization, and input validation.
- Promotes Modular Design: Encapsulates reusable logic in different levels.
- Streamlines Requests: Addresses cross-cutting issues such as logging and caching efficiently.
Best Practices.
- Organize Middleware: Organize middleware logically to reduce redundancy.
- Use Middleware Groups: Combine numerous middleware into a single group for common activities.
- Avoid Heavy Logic: Use lightweight middleware to retain performance.
Example in Action
Create custom middleware:
php artisan make:middleware CheckAge
In the middleware class:
namespace App\Http\Middleware;
use Closure;
class CheckAge
{
public function handle($request, Closure $next)
{
if ($request->age < 18) {
return redirect('home');
}
return $next($request);
}
}
Register the middleware in app/Http/Kernel.php:
protected $routeMiddleware = [
'check.age' => \App\Http\Middleware\CheckAge::class,
];
Apply middleware to routes:
Route::get('/dashboard', [DashboardController::class, 'index'])->middleware('check.age');
This middleware determines the age of the user in the incoming request and moves users under 18 to the home page.