【发布时间】:2016-07-30 11:28:49
【问题描述】:
所以我创建了一个策略并在 AuthServicePRvider 中注册它,但它总是返回 false。这是我第一次使用政策,所以我确信我做错了,但以下几个例子对我没有任何帮助。
我使用 id 为 1 的用户登录。我尝试编辑 user_id 为 1 的标签,返回 false,以及尝试编辑 user_id 为 2 的标签时。最后一个按预期工作,但是如果 user_id 和 label->user_id 匹配,我应该显示一个表单。相反,我每次都得到这个:
This action is unauthorized.
有什么想法吗?
AuthServiceProvider:(都试过了,但都不起作用):
protected $policies = [
'App\Label' => 'App\Policies\LabelPolicy'
];
And this one also did not do the trick:
protected $policies = [
Label::class => LabelPolicy::class
];
标签控制器@编辑:
public function edit(Label $label)
{
// $this->authorize('edit', $label); // This also returns false
if (auth()->user()->cannot('edit', $label)) {
dd('NO'); // This is always shown
}
}
标签政策:
public function edit(Label $label)
{
dd('test'); // This is never shown anywhere
return auth()->user()->id === $label->user_id;
}
【问题讨论】:
-
我标签模型与用户模型有关系,使用它而不是直接访问
user_id:return auth()->user()->id === $label->user->id; -
我认为这个错误
This action is unauthorized.是由于路由问题!如果您有资源控制器。能否请您添加您的路线! -
确实,为标签使用资源控制器:Route::resource('labels', 'LabelsController');
-
我确实有关系,但返回 auth()->user()->id === $label->user->id;也没有用。所以我可能在某个地方还有其他问题,因为我似乎已经正确设置了所有内容,现在也要感谢 Mina 的回答
-
所以当你访问 'lables/edit/some_id' 你会得到
This action is unauthorized.?