How to Display multilevel subcategory of a category using JSON in PHP(Laravel)

In this blog post, I share how to Display the multilevel subcategory of a category using JSON in Laravel you can use it in Core PHP.

For the Android and web applications, we need category, sub-category and child result in JSON format. like this result shown in the image.

Display multilevel subcategory

Here the code is shown in the below code. here I have used a single table for all categories, sub-categories, and children. My table structure looks like this.

My table structure

Here is code:

 $parents = Category::where('parent_id', 0)->get();
        foreach ($parents as $parent) {
            $childs = Category::where('parent_id', $parent->id)->get();
            if (count($childs) > 0) {
                $subCat = array();
                $players = array();
                $roster[$parent->name] = $players;
                        foreach ($childs as $i => $child) {
                            $subchilds = Category::where('parent_id', $child->id)->get();
                            if (count($subchilds) > 0) {

                                $roster[$parent->name][$child->name] = $subCat;
                                foreach ($subchilds as $subchild) {

                                    $roster[$parent->name][$child->name][$subchild->id] = $subchild->name;
                                }

                            }else{
                                $roster[$parent->name][$child->name] = $players;
                            }
                        }

            }
        }
        return $roster;

I hope this will work for you. How to Display multilevel subcategory of a category using JSON in PHP(Laravel)