0
votes

I have a refferal system in my application.ie, One user can reffer other.

Users table

id name 
1   A
2   B
3   C

Referrals table

id referrer_id referee_id
1      1           2
2      2           3

I want to show the referrals made by a user.

User Model

public function referrals()
{
    return $this->hasMany('App\Models\Referral','referee_id','id');
}

Referral Model

public function referrer_user()
{
    return $this->belongsTo('Modules\User\Models\User','referrer_id','id');
}

public function referee_user()
{
    return $this->belongsTo('Modules\User\Models\User','referee_id','id');
}

Defining hasMany relationship in User model and belongsTo relationship in Referrals Model, I'am not getting the desired result.

@foreach($user->referrals as $key => $referral)
    {{dd($referral->referee_user->name)}}
@endforeach

This returning me the name of user itself(referrer) not the referee

1
Are you sure that you are correctly creating a Referral? Maybe you are switching ids upon creation? So far your code seem ok to me. - Desh901
No thats correct - Geethu

1 Answers

1
votes

You are referring the ManyToMany relationship the wrong way.

Anyways, it'll be much easier and efficient the following way.

id  name  referred_by
 1   abc    null
 2   def     1
 3   gfd     2

User Model

/**
 * Who did he bring onboard?
*/
public function referrals(){
  return $this->hasMany('....User', 'referred_by');
}

//Who brought him onboard..
public function referree(){
  return $this->belongsTo('...User', 'referred_by');
}

Just check out the appropriate syntax.