美文网首页
Laravel的用户授权policy

Laravel的用户授权policy

作者: 小慕先森 | 来源:发表于2017-08-12 15:39 被阅读0次

    一、定义策略类
    场景:文章的修改和删除操作

    php artisan make:policy ArticlePolicy
    

    二、编写策略类

    <?php
    
    namespace App\Policies;
    
    use App\Http\Model\Article;
    use App\User;
    use Illuminate\Auth\Access\HandlesAuthorization;
    
    class ArticlePolicy
    {
        use HandlesAuthorization;
    
        /**
         * Create a new policy instance.
         *
         * @return void
         */
        public function __construct()
        {
            //
        }
    
        //修改
        public function update(User $user, Article $article){
            return $user->id === $article->user_id;
        }
        //删除
        public function delete(User $user, Article $article){
            return $user->id === $article->user_id;
        }
    }
    
    

    三、注册策略类和模型关联
    AuthServiceProvider中增加

    protected $policies = [
    //        'App\Model' => 'App\Policies\ModelPolicy',
            'App\Http\Model\Article' => 'App\Policies\ArticlePolicy',
        ];
    

    四、策略判断
    控制器中判断:

    public function update(Article $article){
            $this->authorize('update',$article);
    }
    public function destroy(Article $article){
            $this->authorize('delete',$article);
    }
    

    模板中判断权限:

    @can('update', $article)
                .....
     @endcan
    
    @can('delete', $article)
                .....
     @endcan
    

    相关文章

      网友评论

          本文标题:Laravel的用户授权policy

          本文链接:https://www.haomeiwen.com/subject/lxljrxtx.html