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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

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

Okay