diff --git a/controllers.md b/controllers.md index fe6d706103b..ba09f1947fc 100644 --- a/controllers.md +++ b/controllers.md @@ -14,6 +14,7 @@ - [Localizing Resource URIs](#restful-localizing-resource-uris) - [Supplementing Resource Controllers](#restful-supplementing-resource-controllers) - [Singleton Resource Controllers](#singleton-resource-controllers) + - [Middleware and Resource Controllers](#middleware-and-resource-controllers) - [Dependency Injection and Controllers](#dependency-injection-and-controllers) @@ -538,6 +539,64 @@ Of course, API singleton resources may also be `creatable`, which will register ```php Route::apiSingleton('photos.thumbnail', ProfileController::class)->creatable(); ``` + +### Middleware and Resource Controllers + +Laravel allows you to assign middleware to all, or only specific, methods of resource routes using the `middleware`, `middlewareFor`, and `withoutMiddlewareFor` methods. These methods provide fine-grained control over which middleware is applied to each resource action. + +#### Applying Middleware to all Methods + +You may use the `middleware` method to assign middleware to all routes generated by a resource or singleton resource route: + +```php +Route::resource('users', UserController::class) + ->middleware(['auth', 'verified']); + +Route::singleton('profile', ProfileController::class) + ->middleware('auth'); +``` + +#### Applying Middleware to Specific Methods + +You may use the `middlewareFor` method to assign middleware to one or more specific methods of a given resource controller: + +```php +Route::resource('users', UserController::class) + ->middlewareFor('show', 'auth'); + +Route::apiResource('users', UserController::class) + ->middlewareFor(['show', 'update'], 'auth'); + +Route::resource('users', UserController::class) + ->middlewareFor('show', 'auth') + ->middlewareFor('update', 'auth'); + +Route::apiResource('users', UserController::class) + ->middlewareFor(['show', 'update'], ['auth', 'verified']); +``` + +The `middlewareFor` method may also be used in conjunction with singleton and API singleton resource controllers: + +```php +Route::singleton('profile', ProfileController::class) + ->middlewareFor('show', 'auth'); + +Route::apiSingleton('profile', ProfileController::class) + ->middlewareFor(['show', 'update'], 'auth'); +``` + +#### Excluding Middleware from Specific Methods + +You may use the `withoutMiddlewareFor` method to exclude middleware from specific methods of a resource controller: + +```php +Route::middleware(['auth', 'verified', 'subscribed'])->group(function () { + Route::resource('users', UserController::class) + ->withoutMiddlewareFor('index', ['auth', 'verified']) + ->withoutMiddlewareFor(['create', 'store'], 'verified') + ->withoutMiddlewareFor('destroy', 'subscribed'); +}); +``` ## Dependency Injection and Controllers