I want to return a user with a list of all the people they have referred

Viewed 253

I am developing a referral system in my software. I have gotten the referral right but I want to list all users that have referred someone with the count of people they referred in the admin end.

Here is my user model

public function referrals()
{
    return $this->hasMany(Referral::class, 'user_id', 'id');
}

public function referrer()
{
    return $this->hasOne(Referral::class, 'referred_by', 'id');
}

Note: referred_by is the person that has referred someone and user_id is the person referred

Here is my referral model

protected $fillable = ['user_id', 'referred_by', 'status'];

public function user()
{
    return $this->belongsTo(User::class);
}

Here is my referrals migration

Schema::create('referrals', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned()->references('id')->on('users');
            $table->integer('referred_by')->unsigned()->references('id')->on('users');
            $table->string('status')->nullable();
            $table->timestamps();
        });
1 Answers

You can use has('relationshipName') which limits your results based on the existence of a relationship in your case users that have referred some.

and withCount('relationshipName') which will count the number of results from a relationship without actually loading them.

User::has('referrals')->withCount('referrals')->get()
Related