0

我遇到了一个解决方案,它从控制器中的资源集合中过滤字段CompanyController.php

例如,下面的代码返回所有值,除了company_logo

CompanyResource::collection($companies)->hide(['company_logo']);

公司资源.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;


class CompanyResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */

    protected $withoutFields = [];

    public static function collection($resource)
    {
        return tap(new CompanyResourceCollection($resource), function ($collection) {
            $collection->collects = __CLASS__;
        });
    }

    // Set the keys that are supposed to be filtered out
    public function hide(array $fields)
    {
        $this->withoutFields = $fields;
        return $this;
    }

    // Remove the filtered keys.
    protected function filterFields($array)
    {
        return collect($array)->forget($this->withoutFields)->toArray();
    }

    public function toArray($request)
    {
        return $this->filterFields([
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'telephone' => $this->telephone,
            'company_logo' => $this->company_logo,
            'social_links' => $this->social_links,
            
        ]);
    }

}

现在,我UserResource仍然想指定我不想从相同返回的字段,CompanyResource但它不再是集合中的UserResource

用户资源.php

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'email' => $this->email,
            'status' => $this->status,
            'timezone' => $this->timezone,
            'last_name' => $this->last_name,
            'first_name' => $this->first_name,
            'tags' => TagResource::collection($this->whenLoaded('tags')),
            'company' => new CompanyResource($this->whenLoaded('company')),
            
        ];
    }

所以我的想法是能够在“'company' => new CompanyResource($this->whenLoaded('company')),被困在这里一段时间”上指定排除的字段。

4

1 回答 1

0

经过研究,我找到了解决问题的有效方法

'company' => CompanyResource::make($this->whenLoaded('company'))->hide(['company_logo']),

而不是我无法灵活使用的以下内容:

'company' => new CompanyResource($this->whenLoaded('company')),
于 2021-09-09T18:00:30.337 回答