简介

Gates 是用来判断用户是否有权限执行某个动作的闭包函数。

定义

Gates 通常在 App\Providers\AuthServiceProvider 中定义。

Gates 的第一个参数为用户实例,反对可选参数,如 Eloquent 模型:

public function boot(){    $this->registerPolicies();    // 定义编辑设置的权限    Gate::define('edit-settings', function ($user) {        return $user->isAdmin;    });    // 定义更新文章的权限    Gate::define('update-post', function ($user, $post) {        return $user->id === $post->user_id;    });}
public function boot(){    $this->registerPolicies();    Gate::define('update-post', 'App\Policies\PostPolicy@update');}

应用

if (Gate::allows('edit-settings')) {    // 以后用户能够编辑设置}if (Gate::allows('update-post', $post)) {    // 以后用户能够更新文章}if (Gate::denies('update-post', $post)) {    // 以后用户不能更新文章}if (Gate::forUser($user)->allows('update-post', $post)) {    // 指定用户能够更新文章}if (Gate::forUser($user)->denies('update-post', $post)) {    // 指定用户不能更新文章}

参数上下文

Gate::define('create-post', function ($user, $category, $extraFlag) {    return $category->group > 3 && $extraFlag === true;});if (Gate::check('create-post', [$category, $extraFlag])) {    // The user can create the post...}

受权响应

use Illuminate\Support\Facades\Gate;use Illuminate\Auth\Access\Response;Gate::define('edit-settings', function ($user) {    return $user->isAdmin                ? Response::allow()                : Response::deny('You must be a super administrator.');});
// inspect 获取 Gate 返回的残缺受权响应$response = Gate::inspect('edit-settings', $post);if ($response->allowed()) {    // 以后行为已受权...} else {    echo $response->message();}

受权拦挡

// 在所有其余受权查看之前执行Gate::before(function ($user, $ability) {    if ($user->isSuperAdmin()) {        return true;    }});// 在所有其余受权查看后执行Gate::after(function ($user, $ability, $result, $arguments) {    if ($user->isSuperAdmin()) {        return true;    }});