Middleware in Laravel acts as a filter for HTTP requests entering your application. It allows you to inspect, modify, or reject requests before they reach your routes or controllers.
Middleware has been a core concept in Laravel, inspired by similar patterns in other frameworks, to provide a flexible way of handling request lifecycle logic.
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');
Middleware provides a powerful way to handle requests and enhance application functionality.