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

Generic placeholder image
Brijpal Sharma
php  

Date:-January 17th, 2020 , Posted On:- Web Development


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 application, we need category, sub-category and child result in JSON format. like this result shown in the image.

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

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

display multi level category

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)

About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

0 comments

You must be logged in to post a comment.