首页 > 解决方案 > 如何在不使用策略所属模型的索引上使用策略?

问题描述

我想要做的是对一种控制方法应用一个策略,该方法列出一堆记录,而不是像我见过的大多数示例那样只列出一个记录。

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);

此操作未经授权。

标签: laravelauthorization

解决方案


如前所述:

显然,在 Laravel 文档中,模型类需要传递给不需要模型的操作。所以我很困惑如何使这项工作。

您需要将 theThoughtRecord::class和 the都传递$client到一个数组中:

$this->authorize('view', [ThoughtRecord::class, $client]);


推荐阅读