php - how to get nested category parents and siblings of parents?

469

i'm kind of new to laravel eloquent. i'm creating a system were user can add a post/product and select a category for it. when creating the post i use html -select- to show the first level parents then when user picks one using ajax i load the children of that category in another -select- again when user pick one of the childs using ajax i get the children of that category and append theme to form using -select- so when creating a post everything is ok.

the problem is when user wants to edit the post, i cant display list of categories according to the category user has picked. for example we have this categories:

-laptop
-- asus
---- 11 inches
---- 14 inches
-- apple
---- 11 inches
---- 14 inches
-mobile
-- samsung
---- smart phone
---- tablet
-- apple
---- smart phone
---- tablet

lets say user picked smart phone of apple. when user is editing the post i want to show categories like this:

<select>
    <option>laptop</option>
    <option selected>mobile</option>
</select>
<select>
    <option>samsung</option>
    <option selected>apple</option>
</select>
<select>
    <option selected>smart phone</option>
    <option>tablet</option>
</select>

notice that all parents of the category that user picked are selected.

cats table

id    cat_name    cat_slug    cat_parent

i tried to do something like this but guess i got lost in the middle of it.

function getEditedCategories($catId){
   $cats=[];
   $cat=\App\item_category::with('siblings')->find($catId)->toArray();
   $cats=array_merge($cats,$cat);
   function getCatParent($catParent,$cats,$i){
       $catParent=\App\item_category::with('siblings')->find($catParent)->toArray();
       array_add($cats , 'parents'.$i,$catParent);
       return $catParent['cat_parent'];
   }
   $catParent=$cat['cat_parent'];
   $i=1;
   while(!is_null($catParent)) {
       $i++;
       $catParent = getCatParent($catParent, $cats,$i);
   }
   dd($cats);
}

it's not working and it certainly does not look good.

edited: the result of dd($cats)

array:5 [
"id" => 6
  "cat_name" => "asgas"
  "cat_slug" => "asgasdf"
  "cat_parent" => 5
  "siblings" => array:1 [
    0 => array:4 [
      "id" => 6
      "cat_name" => "asgas"
      "cat_slug" => "asgasdf"
      "cat_parent" => 5
    ]
  ]
]

People are also looking for solutions to the problem: php - Filter is not working when I click on pagination in laravel and mongo db

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.