0

我的应用程序中有一个产品 API 资源,就像这样

    /**
     * Transform the resource collection into an array.
     *
     * @param  Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'desc' => $this->desc,
            'color' => $this->color,
            'amount' => $this->amount,
            'available' => $this->available,
            'createdAt' => $this->created_at,
            'updatedAt' => $this->updated_at,
        ];
    }

我的应用程序中的角色很少,例如管理员、查看者。当管理员访问 api 时,api 返回所有字段,但是当查看者访问 api 时,它只返回有限的字段。

我该如何处理这个使用Gates & Policies

我可以做这样的事情吗

'createdAt' => $this->when($this->authorize('product.list'), $this->created_at)

4

1 回答 1

0

您可以在模型中使用Eloquent AccessorProduct

    public function getCreatedAtAttribute($createdAt)
    {
        if (Gate::allows('see-product-details', $this)) {
            return $createdAt;
        } else {
            return null;
        }
    }

当然你也必须写see-product-details门。

否则这也可以工作(未经测试):

    public function getCreatedAtAttribute($createdAt)
    {
        if ($this->authorize('view', [Product::class, $this])) {
            return $createdAt;
        } else {
            return null;
        }
    }
于 2020-02-05T19:17:26.467 回答