可以在Request类中授权方法为HandlesAuthorization特性返回自定义消息吗?

Pan*_*kaj 8 laravel laravel-5 laravel-request laravel-authorization laravel-5.5

我在Request类中有以下代码来检查用户是否有权执行更新.

HandlesAuthorization trait,默认情况下给出默认消息.有没有办法返回自定义消息?我看到在授权方法Request class可以return boolean只值.

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*łek 7

我相信你不应该看HandlesAuthorization特质。您需要做的就是failedAuthorization在请求类中实现方法。

在FormRequest课堂上,它的定义如下:

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

因此,您需要做的就是在UpdateRoleRequest类中重写此方法,例如:

protected function failedAuthorization()
{
    throw new \Illuminate\Auth\Access\AuthorizationException('User has to be an admin.');
}
Run Code Online (Sandbox Code Playgroud)