Avoid N+1 queries in API resources

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

Tip given by @mmartin_joo

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 79 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials