Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can authorize method in Request class return customized message for HandlesAuthorization trait?

I have the following code in Request class to check if the user is authorized to perform update.

HandlesAuthorization trait, by default gives default message. Is there any way to return customized message? I saw the authorize method in Request class can return boolean value only.

class UpdateRoleRequest extends Request
{
    private $UserPermissionsSession;

    public function __construct(IRole $Role) {
        $this->UserPermissionsSession = new UserPermissionsSession();
    }

    public function authorize() {
        $UserID = \Auth::user()->UserID;
        return $this->UserPermissionsSession->CheckPermissionExists($UserID);
    }

}
like image 693
Pankaj Avatar asked Sep 29 '17 19:09

Pankaj


1 Answers

I believe you shouldn't look at HandlesAuthorization trait. All you need to do is implementing failedAuthorization method in your request class.

In FormRequest class it's defined like this:

/**
 * Handle a failed authorization attempt.
 *
 * @return void
 *
 * @throws \Illuminate\Auth\Access\AuthorizationException
 */
protected function failedAuthorization()
{
    throw new AuthorizationException('This action is unauthorized.');
}

so all you need is to override this method in your UpdateRoleRequest class for example like this:

protected function failedAuthorization()
{
    throw new \Illuminate\Auth\Access\AuthorizationException('User has to be an admin.');
}
like image 61
Marcin Nabiałek Avatar answered Sep 22 '22 02:09

Marcin Nabiałek