【问题标题】:How do I use a policy on an index that doesn't use the model the policy belongs to?如何在不使用策略所属模型的索引上使用策略?
【发布时间】:2020-03-07 00:08:19
【问题描述】:

我正在尝试对一种控制方法应用策略,该方法列出一堆记录,而不是像我见过的大多数示例那样只列出一条记录。

我不想检查ThoughtRecords,而是想在控制器index() 方法中检查登录用户hashedId 到正在查询hashedId 的用户。

显然in the Laravel docs 模型类需要传递给不需要模型的操作。所以我很困惑如何做到这一点。

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

错误

函数 App\Policies\ThoughtRecordPolicy::view() 的参数太少

我也试过了:

$this->authorize('view', $client);

此操作未经授权。

【问题讨论】:

    标签: laravel authorization


    【解决方案1】:

    如前所述:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 2013-07-25
      • 2012-12-22
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多