Closed logusgraphics closed 8 years ago
So I figured out a temporary but clean solution:
I created a recursive function to do the job which toHierarchy()
was supposed to do the right way.
$categories = Category::roots()->get();
function nestChildren($nodes)
{
foreach ($nodes as $node) {
if (count($node->getDescendants()) > 0) {
$node['children'] = $node->getDescendants();
nestChildren($node['children']);
}
}
}
nestChildren($categories);
return Response::json($categories, 200);
So the first line gets all the roots and then I recurse them with the getDescendants()
method. And now I have the correct root array thrown at the REST client.
I'm currently using Baum (which is excellent by the way) to build a category tree structure from a seeded migration.
The method
buildTree($categories)
works great and seeds my pre-populated nested array perfectly.However, when I want my controller to return a JSON array of the tree structure with the method
toHierarchy()
I get the root objects nested inside an object and each object hast a key and value which I can't use to model in my front-end framework (AngularJS).This is the code in my controller:
And this the response I get from my REST Client (Postman):
As you can see it returns an object with nested key,value based objects as the root elements which I can't use to model in AngularJS. I need the root parent to be an array like this: