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 a 403 HTTP error code and the message This action is unauthorized.

To change the custom message, which doesn’t provides a lot of information, what we have to do is use the deny() method from the HandlesAuthorization trait.

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 a 403 HTTP error code but with the message Sorry man, you are not Chuck Norris.

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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.