【问题标题】:Hiding fields in API Resources Using Gates in Laravel在 Laravel 中使用 Gates 隐藏 API 资源中的字段
【发布时间】:2020-05-21 17:02:22
【问题描述】:

我的应用程序中有一个产品 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)

【问题讨论】:

    标签: laravel laravel-api laravel-gate


    【解决方案1】:

    您可以在 Product 模型中使用 Eloquent Accessor

        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-03-30
      • 2019-07-20
      • 2012-03-21
      • 2020-07-20
      • 1970-01-01
      • 2015-07-21
      • 2016-04-16
      • 1970-01-01
      • 2022-12-13
      相关资源
      最近更新 更多