0

I have come across a solution that filters fields from a resource collection in the Controller CompanyController.php

E.g The code below returns all the values except company_logo

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

CompanyResource.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,
            
        ]);
    }

}

Now from my UserResource I still want to specify fields I don't want returned from the same CompanyResource but it's not a collection anymore in the UserResource

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')),
            
        ];
    }

So my idea is to be able to specify excluded fields on 'company' => new CompanyResource($this->whenLoaded('company')), Been stuck here for some time.

1 Answers1

0

After researching I found a working solution for my problem

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

Instead of the below which I could not use flexibly use:

'company' => new CompanyResource($this->whenLoaded('company')),