Laravel的用户授权policy
2017-08-12 本文已影响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