I am trying to build a resource collection with a second resource based on a hasManyThrough relationship. When i call the actual relationship on the main resource it does provide me the correct data. Whenever i pass the data to another resource and use the whenLoaded() method, it doesn't chain the data to the main collection.
The model:
public function fields()
{
return $this->hasManyThrough(Field::class, FieldValue::class, 'component_id', 'id', 'id', 'field_id');
}
The controller:
/**
* @return JsonResponse
*/
public function index()
{
$components = Component::with(['fields'])->get();
return ComponentValueResource::collection($components)->response();
}
ComponentValueResource class:
public function toArray($request)
{
return [
'fields' => FieldResource::collection($this->whenLoaded('fields')),
];
}
FieldResource class:
public function toArray($request)
{
$fields = $this->whenLoaded('fields');
return [
'fields' => new ComponentValueResource($fields),
];
}
Output of dd(FieldResource::collection($this->whenLoaded('fields')));
#original: array:9 [
"id" => 1
"base_id" => 1
"component_id" => null
"identifier" => "text input"
"type" => "text"
"position" => 1
"created_at" => "2021-08-22 19:44:23"
"updated_at" => "2021-08-22 19:44:23"
"laravel_through_key" => 6
]
Output from the resource:
{
"data": [
{
"id": 6,
"fields": [
[]
]
},