I am using etrepat baum laravel module to store and generate hierarchy. Also using eloquent api resource to customize the json data returned.
Currently empty children are returned if no children available. Is it possible to have children only if available?
Current Result
[{
"id": "1",
"text": "Vegetables",
"children": [{
"id": "2",
"text": "Onion",
"children": []
}, {
"id": "3",
"text": "Tomato",
"children": []
}, {
"id": "4",
"text": "Chilli",
"children": []
}, {
"id": "5",
"text": "Potato",
"children": []
}]
}, {
"id": "6",
"text": "Fruits",
"children": [{
"id": "7",
"text": "Apple",
"children": [{
"id": "12",
"text": "Red Apple",
"children": []
}, {
"id": "13",
"text": "Green Apple",
"children": []
}]
}, {
"id": "8",
"text": "Banana",
"children": [{
"id": "14",
"text": "Red Banana",
"children": []
}, {
"id": "15",
"text": "Yellow Banana",
"children": []
}]
}, {
"id": "9",
"text": "Orange",
"children": []
}, {
"id": "10",
"text": "Papaya",
"children": []
}, {
"id": "11",
"text": "Guava",
"children": []
}]
}]
Expected Result
[{
"id": "1",
"text": "Vegetables",
"children": [{
"id": "2",
"text": "Onion"
}, {
"id": "3",
"text": "Tomato"
}, {
"id": "4",
"text": "Chilli"
}, {
"id": "5",
"text": "Potato"
}]
}, {
"id": "6",
"text": "Fruits",
"children": [{
"id": "7",
"text": "Apple",
"children": [{
"id": "12",
"text": "Red Apple"
}, {
"id": "13",
"text": "Green Apple"
}]
}, {
"id": "8",
"text": "Banana",
"children": [{
"id": "14",
"text": "Red Banana"
}, {
"id": "15",
"text": "Yellow Banana"
}]
}, {
"id": "9",
"text": "Orange"
}, {
"id": "10",
"text": "Papaya"
}, {
"id": "11",
"text": "Guava"
}]
}]
CategoryResource.php
public function toArray($request) {
return [
'id' => (string) $this->id,
'text' => (string) $this->name,
'children' => CategoryResource::collection($this->children)
];
}
CategoryController.php
public function index()
{
CategoryResource::withoutWrapping();
$categories = Category::all()->toHierarchy()->values();
return new CategoryResourceCollection($categories);
}