在 laravel 5.1 中,如果使用以下方法,您可以在检查能力时返回自定义响应:
if (Gate::denies('update', $post)) {
return response()->view('errors.403');
}
使用authorize方法时有没有办法返回类似的自定义错误:
$this->authorize('update', $post);
上面只是抛出了一个状态码为 403 的 http 异常。
最佳答案
我可以通过以下方式做到这一点:
在App\Http\Controllers\Controller
中添加以下方法:
protected function createGateUnauthorizedException(
$ability,
$arguments,
$message = 'This action is unauthorized.',
$previousException = null
) {
throw $previousException;
}
它将重新抛出UnauthorizedException
。
现在,在 App\Exceptions\Handler.php
中,您可以在 render
方法的开头添加:
if ($e instanceof \Illuminate\Auth\Access\UnauthorizedException) {
return response()->view('errors.403');
}
关于laravel - 使用 Laravel 5.1 授权方法时如何返回自定义 403 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256000/