阅读(492) (0)

Laravel 8 Gate 响应

2021-06-29 16:33:50 更新

到目前为止,我们只检查了返回简单布尔值的 Gate 。但是,有时你可能希望返回更详细的响应,包括错误消息。为此,你可以从你的 Gate 返回 illuminate\auth\access\response

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

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

从 Gate 返回授权响应时,gate::allows 方法仍将返回一个简单的布尔值。但是可以使用 gate::inspect 方法获取 Gate 返回的完整授权响应:

$response = Gate::inspect('edit-settings', $post);

if ($response->allowed()) {
    // 当前行为已授权...
} else {
    echo $response->message();
} 

当然,当使用 gate::authorize 方法抛出 authorizationexception 时,如果操作未经授权,则授权响应提供的错误消息将传播到 http 响应:

Gate::authorize('edit-settings', $post);

// 当前行为已授权...