Laravel 5.5 权限控制

30 篇文章 1 订阅

权限控制

// Gate
    Gate 是用于判断用户是否有权进行某项操作的闭包,通常使用 Gate 门面定义在 App\Providers\AuthServiceProvider 类中。Gate 总是接收用户实例作为第一个参数,还可以接收相关的 Eloquent 模型实例作为额外参数
    Gate::define('update-post', function ($user, $post) {
            return $user->id == $post->user_id;
        });  // 闭包风格
    
    Gate::define('update-post', 'PostPolicy@update');  // Class@method 风格
    
    Gate::resource('posts', 'PostPolicy');  // 资源 Gate
        [
            Gate::define('posts.view', 'PostPolicy@view');
            Gate::define('posts.create', 'PostPolicy@create');
            Gate::define('posts.update', 'PostPolicy@update');
            Gate::define('posts.delete', 'PostPolicy@delete');
        ]
    
    Gate::resource('posts', 'PostPolicy', [
        'image' => 'updateImage',
        'photo' => 'updatePhoto',
    ]);  // 添加其他权限
    
    (授权动作)
        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)) {
            // 当前用户不能更新文章...
        }


// Policy
    (策略过滤器)
        public function before($user, $ability)
        {
            if ($user->isSuperAdmin()) {
                return true;
            }
        }
    (使用 Policy 授权动作)
        if ($user->can('update', $post)) {
            //
        }
        if ($user->can('create', Post::class)) {  // 不依赖模型的动作
            // Executes the "create" method on the relevant policy...
        }

        $this->authorize('update', $post);
        $this->authorize('create', Post::class);  // 不依赖模型的动作

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值