1

I have laravel 5.5 application and i use gates to authorise users. When the authorisation fails, the response is This action is unauthorized How can i overwrite this response? I want to offer users a custom response.

The way i implemented it is by defining gates in AuthServiceProvider class and then using these gates with the middleware in my routes. In later laravel versions there is something like:

Gate::define('edit-settings', function ($user) {
    return $user->isAdmin
                ? Response::allow()
                : Response::deny('You must be a super administrator.');
});

But allow and deny methods don't exist in Laravel 5.5

marmahan
  • 183
  • 2
  • 15

1 Answers1

1

If you have a look at the HandlesAuthorization policy trait that handles custom messages, you can see that it throws a AuthorizationException with a custom message:

protected function deny($message = 'This action is unauthorized.')
{
    throw new AuthorizationException($message);
}

So you should be able to do the same in your guard, something like this:

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Gate;

Gate::define('edit-settings', function ($user) {
    if (! $user->isAdmin) {
        throw new AuthorizationException('You must be a super administrator.');
    }

    return true;
});
Remul
  • 7,874
  • 1
  • 13
  • 30