You can avoid N+1 queries in API resources by using the whenLoaded()
method. This will only append the department if itβs already loaded in the Employee model. Without whenLoaded()
there is always a query for the department.
class EmployeeResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->uuid,
'fullName' => $this->full_name,
'email' => $this->email,
'jobTitle' => $this->job_title,
'department' => DepartmentResource::make($this->whenLoaded('department')),
];
}
}
Top comments (0)