如何在不使用策略所属模型的索引上使用策略?
How do I use a policy on an index that doesn't use the model the policy belongs to?
我想做的是在列出一堆记录的控制方法上应用策略,而不是像我见过的大多数示例那样只列出一条记录。
我不想检查 ThoughtRecords
,而是想检查已登录的用户 hashedId 到正在控制器 index()
方法中查询 hashedId 的用户。
显然 in the Laravel docs 模型 class 需要传递给不需要模型的操作。所以我很困惑如何进行这项工作。
AuthServiceProvider.php
protected $policies = [
'App\ThoughtRecord' => 'App\Policies\ThoughtRecordPolicy',
];
public function boot()
{
$this->registerPolicies();
}
ThoughtRecordPolicy.php
public function view(User $signedInUser, User $client)
{
//return true;
dd('Policy working');
//return $signedInUser->id === $client->id;
}
ThoughtRecordController.php
public function index($userHashedId)
{
$client = User::where('hashed_id', $userHashedId)->first();
$this->authorize('view', ThoughtRecord::class, $client);
$records = ThoughtRecord::where('user_id', $client->id)->latest()->paginate(1);
return ThoughtRecordResource::collection($records);
}
错误
Too few arguments to function App\Policies\ThoughtRecordPolicy::view()
我也试过:
$this->authorize('view', $client);
This action is unauthorized.
如前所述:
Apparently in the Laravel docs the model class needs to be passed on actions that don't require a model. So I'm confused how to make this work.
您需要将 ThoughtRecord::class
和 $client
都传递到数组中:
$this->authorize('view', [ThoughtRecord::class, $client]);
我想做的是在列出一堆记录的控制方法上应用策略,而不是像我见过的大多数示例那样只列出一条记录。
我不想检查 ThoughtRecords
,而是想检查已登录的用户 hashedId 到正在控制器 index()
方法中查询 hashedId 的用户。
显然 in the Laravel docs 模型 class 需要传递给不需要模型的操作。所以我很困惑如何进行这项工作。
AuthServiceProvider.php
protected $policies = [
'App\ThoughtRecord' => 'App\Policies\ThoughtRecordPolicy',
];
public function boot()
{
$this->registerPolicies();
}
ThoughtRecordPolicy.php
public function view(User $signedInUser, User $client)
{
//return true;
dd('Policy working');
//return $signedInUser->id === $client->id;
}
ThoughtRecordController.php
public function index($userHashedId)
{
$client = User::where('hashed_id', $userHashedId)->first();
$this->authorize('view', ThoughtRecord::class, $client);
$records = ThoughtRecord::where('user_id', $client->id)->latest()->paginate(1);
return ThoughtRecordResource::collection($records);
}
错误
Too few arguments to function App\Policies\ThoughtRecordPolicy::view()
我也试过:
$this->authorize('view', $client);
This action is unauthorized.
如前所述:
Apparently in the Laravel docs the model class needs to be passed on actions that don't require a model. So I'm confused how to make this work.
您需要将 ThoughtRecord::class
和 $client
都传递到数组中:
$this->authorize('view', [ThoughtRecord::class, $client]);