-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[10.x] "Can" validation rule #47371
[10.x] "Can" validation rule #47371
Conversation
Does this not belong in the /**
* Determine if the user is authorized to make this request.
*/
public function authorize() : bool
{
return $this->user()?->can('update-author', $this->route('post')) === true;
} |
@johanrosenson This would prevent the whole request in case the user is not authorized to update the author. The So User X may update a post (title and body) but may not update the author of the post – only admins are allowed to do that for example. Another way to achieve this would be to use a custom closure based validation rule or the |
@dennisprudlo true, I think it just feels weird for me to put authorization checks together with input validation. |
It's kind of a chicken/egg thing. The request flow is authorize, then validate. But in order to authorize, you need to check that the input exists. This can be handled in a Request's There's no perfect solution for it. |
Love this! Although this is how I'd currently achieve it, using the return [
'author' => $this->user()->can('update-author', $this->post) ? '' : 'missing',
...
] |
Description
This PR implements a new "can" validation rule (accessible via the
Rule::can
method).It provides a way to authorize an ability for a given form field.
Usage
Given the following
PostPolicy
that ensures only admins can change a blog post's author:And a
PostRequest
that allows the user to change the author if it's present, we can validate that the user has the ability to do so using theRule::can()
method:This allows us to move this validation from the controller and into the form request:
Notes
The validation rule will always include the submitted field's value in the authorization method, but it will be pushed to the end when given more arguments, allowing developers to send their own values to authorization methods that will take precedence. This offers compatibility to raw Gate definitions, as well as model policies.
For the example below, we don't provide any additional arguments in the
Rule::can()
method after the ability, so the second argument in the gate definition's callback is the field's value:Using the same example, if we add new arguments into the
Rule::can()
method, the$fieldValue
will be last:Let me know if you have any issues or concerns with this PR. No hard feelings on closure ❤️
Thanks for your time!