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
1class EmplyeeResource extends JsonResource 2{ 3 public function toArray($request): array 4 { 5 return [ 6 'id' => $this->uuid, 7 'fullName' => $this->full_name, 8 'email' => $this->email, 9 'jobTitle' => $this->job_title,10 'department' => DepartmentResource::make($this->whenLoaded('department')),11 ];12 }13}
Tip given by @mmartin_joo