Custom authorization error messages in Laravel Gates
Pre-requisites: Previous knowledge about Gates and how it works.
In this post, I will show you how to return custom messages in your Gates policies using the HandlesAuthorization trait.
First, let’s create a policy using artisan with:
php artisan make:policy MachineGunPolicy
Now, in the MachineGunPolicy we are going to create the “canUseIt” method like the following:
public function canUseIt(User $user, MachineGun $machineGun) { if ($user->isChuckNorris()) { return true; } return false; }
If the given authenticated user is not “Chuck Norris” the policy will return an Illuminate\Auth\Access\AuthorizationException with
To change the custom message, which doesn’t
The following code will do the magic:
public function canUseIt(User $user, MachineGun $machineGun) { if ($user->isChuckNorris()) { return true; } $this->deny('Sorry man, you are not Chuck Norris'); }
Then, when the policy fails it will return an Illuminate\Auth\Access\AuthorizationException with
So that’s it, you are ready to go, you can define a different message for every method you want, or use the one by default.