One solution to this problem is to add a parameter to the EmployeeResource class constructor that indicates whether the resource is being loaded from another resource or not. If it is being loaded from another resource, then the gender attribute can be excluded from the response. Here's an example implementation:
class EmployeeResource extends JsonResource
{
private $isLoadedFromAnotherResource;
public function __construct($resource, $isLoadedFromAnotherResource = false)
{
parent::__construct($resource);
$this->isLoadedFromAnotherResource = $isLoadedFromAnotherResource;
}
public function toArray(Request $request): array
{
$data = [
'id' => $this->id,
'name' => $this->name,
];
if (!$this->isLoadedFromAnotherResource) {
$data['gender'] = GenderResource::make($this->gender);
}
return $data;
}
}
Then, in the GenderResource class, when creating the EmployeeResource instances, pass true as the second parameter to indicate that they are being loaded from another resource:
class GenderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'employees' => EmployeeCollection::make($this->whenLoaded('employees', function () {
return EmployeeResource::collection($this->employees)->map(function ($employee) {
return new EmployeeResource($employee, true);
});
})),
];
}
}
This way, when the EmployeeResource is being loaded from the GenderResource, the gender attribute will be excluded from the response.