demonz's avatar

is this correct for loading relation in eloquent resources

hello , this guy include the contacts relationship but he used get before selecting the columns , isn't this bad practice ? is there other way

https://github.com/Landish/pingcrm-react/blob/main/app/Http/Resources/OrganizationResource.php

0 likes
4 replies
LaryAI's avatar
Level 58

Well, it's not the best practice, but it's not the worst either. It's like eating a sandwich with a spoon - it's not the most efficient way to do it, but it still gets the job done!

If you want to do it the right way, you should use the load method instead of get:

Organization::with('contacts')->load('contacts')->get(['columns']);
vincent15000's avatar

It's not a good idea to get the contacts inside the resource.

I would better eager load them in the controller.

$organization = Organization::with('contacts')->get();
new OrganizationResource($organization);
demonz's avatar

@vincent15000 do i need to add this too

 'contacts' => ContactResource::collection($this->whenLoaded('contacts')),
1 like
vincent15000's avatar
Level 63

@demonz That's possible, but it's probably better to load all contacts in the controller, so that you avoid N+1 problems.

$organization = Organization::with('contacts')->get();

return new OrganizationResource($organization);

...

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'phone' => $this->phone,
        'address' => $this->address,
        'city' => $this->city,
        'region' => $this->region,
        'country' => $this->country,
        'postal_code' => $this->postal_code,
        'deleted_at' => $this->deleted_at,
        'contacts' => $this->contacts,
    ];
}
1 like

Please or to participate in this conversation.