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

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

Like our articles?

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