权限控制
// 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); // 不依赖模型的动作