|
8 | 8 | - [Checking Features](#checking-features)
|
9 | 9 | - [Conditional Execution](#conditional-execution)
|
10 | 10 | - [Blade Directive](#blade-directive)
|
| 11 | + - [Middleware](#middleware) |
11 | 12 | - [In-Memory Cache](#in-memory-cache)
|
12 | 13 | - [Scope](#scope)
|
13 | 14 | - [Specifying The Scope](#specifying-the-scope)
|
@@ -276,6 +277,53 @@ To make checking features in Blade a seamless experience, Pennant offers a `@fea
|
276 | 277 | @endfeature
|
277 | 278 | ```
|
278 | 279 |
|
| 280 | +<a name="middleware"></a> |
| 281 | +### Middleware |
| 282 | + |
| 283 | +Pennant also includes a [middleware](/docs/{{version}}/middleware) that may be used to verify the currently authenticated user has access to a feature before a route is even invoked. To get started, you should add a middleware alias for the `EnsureFeaturesAreActive` middleware to your application's `app/Http/Kernel.php` file: |
| 284 | + |
| 285 | +```php |
| 286 | +use Laravel\Pennant\Middleware\EnsureFeaturesAreActive; |
| 287 | + |
| 288 | +protected $middlewareAliases = [ |
| 289 | + // ... |
| 290 | + 'features' => EnsureFeaturesAreActive::class, |
| 291 | +]; |
| 292 | +``` |
| 293 | + |
| 294 | +Next, you may assign the middleware to a route and specify the features that are required to access the route. If any of the specified features are inactive for the currently authenticated user, a `400 Bad Request` HTTP response will be returned by the route. Multiple features may be specified using a comma-delimited list: |
| 295 | + |
| 296 | +```php |
| 297 | +Route::get('/api/servers', function () { |
| 298 | + // ... |
| 299 | +})->middleware(['features:new-api,servers-api']); |
| 300 | +``` |
| 301 | + |
| 302 | +<a name="customizing-the-response"></a> |
| 303 | +#### Customizing The Response |
| 304 | + |
| 305 | +If you would like to customize the response that is returned by the middleware when one of the listed features is inactive, you may use the `whenInvalid` method provided by the `EnsureFeaturesAreActive` middleware. Typically, this method should be invoked within the `boot` method of one of your application's service providers: |
| 306 | + |
| 307 | +```php |
| 308 | +use Illuminate\Http\Request; |
| 309 | +use Illuminate\Http\Response; |
| 310 | +use Laravel\Pennant\Middleware\EnsureFeaturesAreActive; |
| 311 | + |
| 312 | +/** |
| 313 | + * Bootstrap any application services. |
| 314 | + */ |
| 315 | +public function boot(): void |
| 316 | +{ |
| 317 | + EnsureFeaturesAreActive::whenInactive( |
| 318 | + function (Request $request, array $features) { |
| 319 | + return new Response(status: 403); |
| 320 | + } |
| 321 | + ); |
| 322 | + |
| 323 | + // ... |
| 324 | +} |
| 325 | +``` |
| 326 | + |
279 | 327 | <a name="in-memory-cache"></a>
|
280 | 328 | ### In-Memory Cache
|
281 | 329 |
|
|
0 commit comments