DEV Community

Cover image for Laravel: Avoid N+1 queries in API resources
Akhilesh Gupta
Akhilesh Gupta

Posted on

Laravel: 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')),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay