0

I am working on a MLM System, i want to get all childs & subchilds of any parent user. i tried use of recursion but failed. please help me to solve this.

public function searchAllDownline(Request $req){
 $ids = array();
 $req->validate(['search_keyword'=>'required']);
 $search_keyword = $req->search_keyword;
 $position = $req->position;
 $user = User::where('username',$search_keyword)->first();
  if(empty($user)){
    return back()->with('error','Invalid username'); 
  }
  $query = User::where('parent_id',$user->id)->where('position',$position)->get();
   foreach($query as $data){
    $ids[] = $data->id; 
   }
   $depth = User::where('name','!=','')->max('depth') - $user->depth - 2;
   $this->recursion($ids,$position,$depth);
  
  return view('admin.all-downline',compact('search_result','search_keyword','position'));

}

public function recursion($ids,$position,$depth){
         $subquery = User::whereIn('parent_id',$ids)->where('position',$position)->get();
          foreach($subquery as $subdata){
           array_push($ids,$subdata->id); 
         }
         while($depth-- != 0){
          $this->recursion($ids,$position,$depth);
         }

         print_r(array_unique($ids));
   }

Table structure: enter image description here

Saim Khan
  • 31
  • 1
  • 3

1 Answers1

1

There is a quite useful answer you can try below (can’t comment without enough rep…):

https://stackoverflow.com/a/26654139/19766732

It’s old but gold ;)

Ksi
  • 179
  • 4