-2

i have a MLM system. where User hasmany Users. now i want to get all users of root/ lavel-1 user and where one user hasmany user and each of the users can hasmany user (in deep) laravel.

Here Is relation in model:

    //    All Child Refer
    public function referral_child_users()
    {
        return $this->hasMany(User::class, 'ref_by', 'id')->select('id', 'username', 'ref_by');[!
    }

    //    All Child Refer
    public function referral_multilevel_child_users()
    {
        return $this->referral_child_users()
        ->with('referral_multilevel_child_users');
    }

in Controller:

$user = User::with('referral_multilevel_child_users')->select('id', 'username', 'ref_by')->find(Auth::user()->id);

then i got an error: Undefined array key 0

for example: i want all count of users whose prime parent is A

enter image description here

Rajib Bin Alam
  • 353
  • 1
  • 4
  • 16
  • Where did the error come from? Have you confirmed your relationship is actually working as expected? – miken32 Apr 16 '23 at 22:24

2 Answers2

0

It seems that the way you use the query to fetch data cause the result

Check this out:

$user = \Auth::user();
        $users = User::where('ref_by', $user->id)
            ->orWhereHas('referral_multilevel_child_users', function ($query) use ($user) {
                $query->where('ref_by', $user->id);
            })
            ->get();
Mahdi Rashidi
  • 411
  • 3
  • 8
0

Change the with function ->with(['referral_multilevel_child_users']);

    //    All Child Refer
    public function referral_multilevel_child_users()
    {
        return $this->referral_child_users()
        ->with(['referral_multilevel_child_users']);
    }
Rajib Bin Alam
  • 353
  • 1
  • 4
  • 16