Laravel 权限控制基础之Gate 和Policy

policy和Gate
php artisan make:policy PostPolicy –model=Post //特定model
//AuthServiceProvider.php在定义权限
//Gate::define(‘view-post’, ‘ClassName@methodOne’);
Gate::define(‘show-info’, function ($test, $post) {
return $test->owns($post);
});
//user.php
public function owns($post)
{
return $this->id == $post->user_id;
}
//控制器
use Gate;
auth()->loginUsingId(1);
$test = TestModel::findOrFail(1);
//Gate::allows();//判断是否允许
if(Gate::denies(‘show-info’,$test)) {
echo ‘禁止访问’;
} else {
echo ‘允许访问’;
}
//可以用policy替换Gate
//AuthServiceProvider.php
protected $policies = [
‘app\Models\TestModel’ => ‘app\Policies\PostPolicy’,
];
$user = auth()->loginUsingId(1);
$test = TestModel::findOrFail(1);
echo $user->id;
echo $test->user_id;
if ($user->cannot(‘show-info’, $test)) {
echo ‘禁止访问’;
} else {
echo ‘允许访问’;
}
对于Gate来定义和policy替换, 在一个项目中通常两种方式都使用,如果访问控制的逻辑非常简单,且只需用到一个方法,那么直接写成Gate的闭包即可,如果比较复杂,且需要对模型进行多个方法的权限控制,那么就写成policy



Tagged , , . Bookmark the permalink.

Comments are closed.