How to return custom 403 exception when using Lara

2019-07-13 12:33发布

问题:

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