How can I return the child collection of a collection in Laravel 5.7? I have a Laravel collection that itself contains a collection. When I return the parent collection through my api, there is clearly a "children" object, but when I try to return the "children" object it is null.
Relevant collection code:
$item = [
'id' => $this->id,
...
$this->mergeWhen($this->type === Item::[type], [
...
'children' => [type]::collection($this->[prop])
]),
...
return $item;
];
Relevant api controller code:
$itemsQuery = $[parent_type]->items()->topLevel()->withAll()->ordered()->get();
$items = [type]::collection($itemsQuery);
$return_array = [];
foreach ($items as $item)
{
array_push($return_array, $item);
}
return $return_array;
This returns what I would expect.
"data": {
"id": [guid],
...
"children": [
{
"id": [guid],
...
}
]
}
but when I change it to
$itemsQuery = $[parent_type]->items()->topLevel()->withAll()->ordered()->get();
$items = [type]::collection($itemsQuery);
$return_array = [];
foreach ($items as $item)
{
array_push($return_array, $item->children);
}
return $return_array;
I get
"data": null
Try this :
...
$return_array = collect();
foreach ($items as $item)
{
$return_array->push($item->children);
}
return $return_array->toArray();
有一个collect()
助手,不确定它是否会帮助您,但是您可以通过这种方式将基本数组转换为集合。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.