一、创建 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
修改: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;
}
发现正常返回