I am working on a referral system, when a user shares his referral link to a guest, and the guest registers the user will be given a bonus (working as expected), but now what I am trying to do is
I would like to give a bonus to the first user that referred a user
For example:
A referred B and
B referred C
Anytime B referred a new user give A bonus
So if C referred a new user give B bonus
Below is my code:
$referrer = User::whereUsername(session()->pull('referrer'))->first();
$user = User::create([
'username' => $request->username,
'name' => $request->name,
'referrer_id' => $referrer ? $referrer->id : null,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
if ($user->referrer !== null)
{
$user->referrer->deposit(400);
// Notification::send($user->referrer, new ReferrerBonus($user));
}
On model:
/**
* A user has a referrer.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function referrer()
{
return $this->belongsTo(User::class, 'referrer_id', 'id');
}
/**
* A user has many referrals.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function referrals()
{
return $this->hasMany(User::class, 'referrer_id', 'id');
}
On migration file:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('username')->unique();
$table->unsignedBigInteger('referrer_id')->nullable();
$table->foreign('referrer_id')->references('id')->on('users');
$table->string('email')->unique();
$table->integer('is_admin')->default(0);
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});