laravel - 如何在不使用策略所属模型的索引上使用策略?
问题描述
我想要做的是对一种控制方法应用一个策略,该方法列出一堆记录,而不是像我见过的大多数示例那样只列出一个记录。
ThoughtRecords
我不想检查登录用户 hashedId 来检查控制器方法中正在查询 hashedId 的用户index()
。
显然,在 Laravel 文档中,模型类需要传递给不需要模型的操作。所以我很困惑如何使这项工作。
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;
}
思想记录控制器.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);
}
错误
函数 App\Policies\ThoughtRecordPolicy::view() 的参数太少
我也试过:
$this->authorize('view', $client);
此操作未经授权。
解决方案
如前所述:
显然,在 Laravel 文档中,模型类需要传递给不需要模型的操作。所以我很困惑如何使这项工作。
您需要将 theThoughtRecord::class
和 the都传递$client
到一个数组中:
$this->authorize('view', [ThoughtRecord::class, $client]);
推荐阅读
- ruby - 如何制作一个 Ruby 方法来制作具有“n”宽度的星号钻石?
- python - 使精灵在点击时消失
- sql - 通过在 Hive/Athena 的 CSV 文件中添加两列来创建外部表
- android - 深度链接在 chrome expo react native 项目中不起作用
- python - 在 MacOS Big Sur 上安装 Python3.4 时出错
- powershell - 创建 NotifyIcon 并使用 powershell 处理单击事件
- typescript - 数组 concat 的返回类型
- android - 如何在 ViewModel 中使用 Strings.xml 而无需在 Android 中使用上下文?
- java - Spring WebClient 下载 PDF 会出现 HTTP 错误
- sql - SQL - 记录案例记录中的状态变化