【发布时间】:2019-07-14 16:33:44
【问题描述】:
我正在使用 laravel 基本策略系统来保护未经授权的用户免受更新帖子的影响。例如用户的 ID 为 1,在帖子中表 User_id 也是 1。
现在以$this->authorize('update',$post); 的方式,我只能通过一个变量$post 进行身份验证。而在can 方法中,我也可以使用$user 变量$user->can('update',$post) 进行授权。
代码如下:
在 PostPolicy.php 中:
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
在 AuthServiceProvider.php 中:
protected $policies = [
Post::class => PostPolicy::class
]
在控制器授权方式:
public function update(Request $request, $id)
{
$post=Post::find(1);
$user=User::find(1);
$this->authorize('update',$post);
return 'Hello Everything Access For You ';
}
在Controller中使用can方法:
public function update(Request $request, $id)
{
$post=Post::find(1);
$user=User::find(1);
if($user->can('update',$post)){
return 'Your are allowed';
}
else
{
return 'Your are Not allowed';
}
}
我是否适合这两个功能。有没有区别。我必须使用哪种方法。提前致谢。
【问题讨论】:
-
根据文档,它们在引擎盖下是相同的。用户模型具有
can函数。控制器有一个authorize。两者都使用基础策略。 -
如果它们在底层是相同的,那么为什么我不能将 $user 变量传递给
$this->authorize('update',$user,$post) -
因为
authorize用于授权the current user。 -
但在某些情况下我不想使用当前用户。并使用不同的用户进行检查。尝试了解我喜欢 $this->authorize 功能,但缺少一些齿轮。
-
这就是
can的用途。如果您在$user中有任何用户模型,请使用$user->can()。
标签: php laravel laravel-5 laravel-4 laravel-5.2