Middleware Groups in Laravel allow you to bundle multiple middleware together and apply them to a set of routes or controllers. This simplifies the application of commonly used middleware combinations, such as those for web and API routes.
Middleware Groups were introduced in Laravel to provide a cleaner way to apply multiple middleware to routes, improving readability and reducing redundancy in route definitions.
web
and api
groups as starting points.Define a custom middleware group in app/Http/Kernel.php
:
protected $middlewareGroups = [
'admin' => [
App\Http\Middleware\Authenticate::class,
App\Http\Middleware\LogAdminActivity::class,
],
];
Apply the group to routes:
Route::middleware(['admin'])->group(function () {
Route::get('/dashboard', [AdminController::class, 'index']);
});
This ensures all routes in the group share the same middleware stack.