The vast majority of our policy methods return a boolean result. They just tell us if the user can perform a specific action on a model or not.
We then leverage these policies in a form request, to quickly authorize an action for a user. It's as simple as:
// in your form request
public function authorize()
{
return $this->user()->can('update', $this->route('company'));
}
But in one of our policies, we had a requirement to reject the request with a specific error message in one particular branch of the policy check.
So now our policy could return either a boolean or a Response
object.
My normal policy check in the form request will no longer work, because the can
method discards the response and only returns a boolean.
I looked at the other methods available from the user object, but they all return a boolean as well.
If I stop trying to authorize from the user object, and instead use the Gate
facade, I now get access to quite a few more methods, some of which support returning a Response
object.
The authorization code now becomes:
// in your form request
public function authorize()
{
return Gate::authorize('update', $this->route('company'));
}
This method always return a Response
.
Even if my policy method returns a boolean, the Gate
will convert it to either Response::deny()
or Response::allow()
for a consistent return type.
Here to help,
Joel
P.S. Form requests are great for both authorization and validation. If you want to level up your validation logic, check out our book Mastering Laravel Validation Rules.