Laravel 门自定义响应

Laravel Gate custom response

我有 laravel 5.5 应用程序,我使用 gates 来授权用户。当授权失败时,响应是 This action is unauthorized 如何覆盖这个响应?我想为用户提供自定义响应。

我实现它的方式是在 AuthServiceProvider class 中定义门,然后在我的路由中将这些门与中间件一起使用。在后来的 laravel 版本中有类似的东西:

Gate::define('edit-settings', function ($user) {
    return $user->isAdmin
                ? Response::allow()
                : Response::deny('You must be a super administrator.');
});

但是 Laravel 5.5

中不存在 allow 和 deny 方法

如果您查看处理自定义消息的 HandlesAuthorization 策略特征,您可以看到它会抛出带有自定义消息的 AuthorizationException

protected function deny($message = 'This action is unauthorized.')
{
    throw new AuthorizationException($message);
}

所以你应该可以在你的守卫中做同样的事情,像这样:

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Gate;

Gate::define('edit-settings', function ($user) {
    if (! $user->isAdmin) {
        throw new AuthorizationException('You must be a super administrator.');
    }

    return true;
});