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);
}
You can check before adding it to the array and if it's empty don't add it to the returned array :
public function toArray($request) {
$result = [
'id' => (string) $this->id,
'text' => (string) $this->name
];
$child = CategoryResource::collection($this->children);
if (!$child->isEmpty()) {
$result['children'] = $child;
}
return $result;
}
In Laravel 5.7, you could use:
public function toArray($request) {
return [
'id' => (string) $this->id,
'text' => (string) $this->name,
'children' => CategoryResource::collection($this->whenLoaded('children'))
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With