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)