Custom message on Laravel policy authorization
Answer was given in comments, put here for reference:
Laravel provides this functionality through the deny()
function in the HandlesAuthorization
trait. The deny()
function throws an UnauthorizedException
but allows you to specify a message instead of throwing a plain exception.
Replace the return false
with it and you can send custom messages to render in the exception handler.
Example:
public function reply(User $user)
{
if ($user->current_level < 3) {
$this->deny('Sorry, your level is not high enough to do that!');
// Laravel 6+ requires you to return the deny(), see following line
// return $this->deny('Sorry, your level is not high enough to do that!');
}
return true;
}