Skip to content

Commit b90de31

Browse files
committed
pennant middleware
1 parent 7f37ebd commit b90de31

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

pennant.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
- [Checking Features](#checking-features)
99
- [Conditional Execution](#conditional-execution)
1010
- [Blade Directive](#blade-directive)
11+
- [Middleware](#middleware)
1112
- [In-Memory Cache](#in-memory-cache)
1213
- [Scope](#scope)
1314
- [Specifying The Scope](#specifying-the-scope)
@@ -276,6 +277,53 @@ To make checking features in Blade a seamless experience, Pennant offers a `@fea
276277
@endfeature
277278
```
278279

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+
279327
<a name="in-memory-cache"></a>
280328
### In-Memory Cache
281329

0 commit comments

Comments
 (0)