vendredi 3 janvier 2020

How to get child under sub-category and sub-category user category in JSON Laravel

This very common question but I am not able to make it in JSON Format for API. I a Table Category where I stored three layers of Category. Category->subcategory->child. I want to get this in API in Format.

Something like.

Category

  sub-category-1
  sub-category-2 
      child-2-1
      child-2-2
  sub-category-3

I try with code

  $allData = array();
            // get all parent category 
            $categories = Category::where(['status' => 1, 'parent_id' => 0])->get();        
            foreach ($categories as $key=>$sub) {
                    // now take one by one it's child category 
                    $allData[$key]['parent'] = $sub->name;
                    $subCategory = Category::where('status', 1)->where('parent_id', '=', $sub->id)->get();
                    $subCat = array();
                    // set parent category title
                    foreach ($subCategory as $k=>$subcat) {
                        $subCat[$subcat->id] = $subcat->name;

                    }
                    // set child category array
                    $allData[$key]['child'] = $subCat;
            }
           return $allData;

I got this result not I don't know how to get child value

enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire