Can you show how $data is created?
Sep 29, 2022
6
Level 1
Trouble retrieving JSON data from API
Hi there! It's my first time using Laravel as an API, and I can't understand this odd behavior: for some reason I get all my JSON structure with the keys, but all the values are null.
See, this is my API response:
[
{
"title": null,
"url": null,
"children": [
{
"title": null,
"url": null
}
]
},
{
"title": null,
"url": null
}
]
And when i dd() the data before it gets send, everything is normal:
array:2 [▼
0 => array:3 [▼
"title" => "Menu item 1"
"url" => "/item-1"
"children" => array:1 [▼
0 => array:2 [▼
"title" => "Menu item 2"
"url" => "/item-3"
]
]
]
1 => array:2 [▼
"title" => "Menu item 3"
"url" => "/item-2"
]
]
This is the response statement, which sends the above structure:
return response()->json($data, 200);
Appreciate the help!
Level 1
Got it. To end my monolog, I let the adaptation of the treeToArray() function that made it work.
public function treeToArray(Collection $tree)
{
if (!$tree->count()) {
return null;
} else {
return array_map(function ($item) {
$trans = $item->translations->whereIn('locale', 'pt-BR')->first();
$data = array();
$data['title'] = $trans->title;
$data['url'] = $trans->url;
if ($item->descendants()->count() > 0) {
$data['children'] = self::treeToArray($item->descendants()->withdepth()->get());
}
return $data;
}, $tree->all());
}
}
Please or to participate in this conversation.