2

在 laravel 5.1 中,如果您使用以下方法,您可以在检查能力时返回自定义响应:

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

使用授权方法时有什么方法可以返回类似的自定义错误:

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

以上只是抛出一个状态码为 403 的 http 异常。

4

1 回答 1

5

我可以通过以下方式做到这一点:

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');
}
于 2015-12-13T21:33:32.750 回答