laravel5.1-第10.2章-RBAC-policy laravel5.1-第10.2章-RBAC-policy

2023-07-06

一、创建 policy

php artisan make:policy PostPolicy

修改创建的文件:app/policies/PostPolicy.php

use App\Post;
use App\User;

public function update(User $user, Post $post)
{
   return $user->owns($post);
}

修改:app/Providers/AuthServiceProvider.php

protected $policies = [
   'App\Post' => 'App\Policies\PostPolicy',
];

public function boot(GateContract $gate)
{
   $this->registerPolicies($gate);
}

修改:

public function show($id)
{
   $post = Post::findOrFail($id);
   \Auth::loginUsingId(2);
   $this->authorize('update', $post);
   return $post->title;
}

二、测试

访问:http://localhost:8000/posts/1

https://file.lulublog.cn/images/3/2023/07/v5A646Q3lN64LlDEA1LE20Q1hzdB11.jpg

修改:app/Http/Controllers/PostsController.php,登录 id=1 的用户

public function show($id)
{
   $post = Post::findOrFail($id);
   \Auth::loginUsingId(1);
   $this->authorize('update', $post);
   return $post->title;
}

发现正常返回

阅读 475