diff --git a/authorization.md b/authorization.md index 35b716df..9c4b51d5 100644 --- a/authorization.md +++ b/authorization.md @@ -355,9 +355,29 @@ In addition to helpful methods provided to the `User` model, Laravel provides a } } +#### Actions That Don't Require Models + +As previously discussed, some actions like `create` may not require a model instance. In these situations, you may pass a class name to the `authorize` method. The class name will be used to determine which policy to use when authorizing the action: + + /** + * Create a new blog post. + * + * @param Request $request + * @return Response + * @throws \Illuminate\Auth\Access\AuthorizationException + */ + public function create(Request $request) + { + $this->authorize('create', Post::class); + + // The current user can create blog posts... + } + #### Authorizing Resource Controllers -When authorizing resources through a resource controller you can make use of the `authorizeResource` method in the controller's constructor. This will allow you to fully protect the resource controller methods with a single line of code. +If you are utilizing [resource controllers](/docs/{{version}}/controllers##resource-controllers), you may make use of the `authorizeResource` method in the controller's constructor. This method will attach the appropriate `can` middleware definition to the resource controller's methods. + +The `authorizeResource` method accepts the model's class name as its first argument, and the name of the route / request parameter that will contain the model's ID as its second argument: authorize('create', Post::class); - - // The current user can create blog posts... - } +> {tip} You may use the `policy:make` command with the `--model` option to quickly generate a policy class for a given model: `php artisan policy:make --model=Post`. ### Via Blade Templates