In Laravel I'm generating serialized responses using resource classes. I have the following resources: JobOffer and Business. Here is JobOfferResource::toArray method
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'title' => $this->title,
...
'business' => new BusinessResource($this->whenLoaded('business')),
...
];
}
And here's BusinessResource::toArray
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'logo' => $this->logo,
...
];
}
What would be the best way to limit fields in JobOfferResource in collection case? For example
GET /api/v1/job_offer/{id}
{
id: id,
title: title,
...
business: {
id: business_id,
name: name,
address: address,
logo: logo,
...
}
}
But JobOfferCollection has limited fields for Business
GET /api/v1/job_offer
[
{
id: id,
title: title,
...
business: {
name: name,
address: address,
logo: logo
},
},
...
]
So far I came up with several ways
- Create new resources like \Short\JobOfferResource->\Short\BusinessResource and have limited fields there
- Create JobOfferCollection resource and run over collection limiting those fields manually
- Use Resource::additional method to add parameters, like
return JobResource::collection($jobOffer::all())->additional(['short' => true]);
public function toArray(Request $request): array
{
return [
'id' => $this->when(!$this->short, $this->id),
'name' => $this->name,
'address' => $this->address,
'logo' => $this->logo,
'field' => $this->when($this->short, $this->field),
];
}
- Modify existing parent Resource class, as well as my classes as follows
protected bool $short = false;
public function setShort(bool $short): static
{
$this->$short = $short;
return $this;
}
public function toArray(Request $request): array
{
return [
'id' => $this->when(!$this->short, $this->id),
'name' => $this->name,
'address' => $this->address,
'logo' => $this->logo,
'field' => $this->when($this->short, $this->field),
];
}
public function toArray(Request $request): array
{
return [
...
'business' => new BusinessResource($this->whenLoaded('business'))->setShort($this->short),
...
];
}
What can I try next?