ContactResource::collection($this->contacts)
Oct 19, 2022
31
Level 7
relationship resource file and how to include that to show an array of contact for company?
Hi I currently have a relationship between two tables, Contacts Companies
Great I am getting an object of company for each contact but when I try and get an an array of contacts for each company I'm just getting NULL back?! company resource:
<?php
namespace App\Http\Resources;
use App\Http\Resources\ContactResource;
use Illuminate\Http\Resources\Json\JsonResource;
class CompanyResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
"id" => $this->id,
"name" => $this->name,
"email" => $this->email,
"phone" => $this->phone,
"address" => $this->address,
"town_city" => $this->town_city,
"region_county" => $this->region_county,
"country_code" => $this->country_code,
"post_code" => $this->post_code,
"contacts" => new ContactResource($this->contact)
];
}
}
Company model:
public function contacts() {
return $this->hasMany(Contact::class, 'contact_id', 'id');
}
Level 104
@boyjarv ok I believe you are getting an infinite loop because the ContactResource returns the CompanyResource, and the CompanyResource returns the ContactResource and so on...
You can instead conditionally load either
Please or to participate in this conversation.