How to return custom 403 exception when using Laravel 5.1 authorize method

假装没事ソ 提交于 2019-12-11 01:18:47

问题


In laravel 5.1 you can return a custom response when you check abilities if you use the following method:

if (Gate::denies('update', $post)) {
        return response()->view('errors.403');
}

Is there any way to return a similar custom error when using the authorize method:

$this->authorize('update', $post);

The above simply throws a http exception with status code 403.


回答1:


I can do it in following way:

In App\Http\Controllers\Controller add the following method:

protected function createGateUnauthorizedException(
    $ability,
    $arguments,
    $message = 'This action is unauthorized.',
    $previousException = null
) {
    throw $previousException;
}

It will rethrow UnauthorizedException.

Now in App\Exceptions\Handler.php you can add at the beginning of render method:

if ($e instanceof \Illuminate\Auth\Access\UnauthorizedException)  {
    return response()->view('errors.403');
}


来源:https://stackoverflow.com/questions/34256000/how-to-return-custom-403-exception-when-using-laravel-5-1-authorize-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!