Laravel的用户授权policy

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

php artisan make:policy ArticlePolicy

二、编写策略类

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)