Skip to content

Instantly share code, notes, and snippets.

@rajibbinalam
Created August 14, 2024 07:42
Show Gist options
  • Save rajibbinalam/fe4405b87335ad32c56d678257689b61 to your computer and use it in GitHub Desktop.
Save rajibbinalam/fe4405b87335ad32c56d678257689b61 to your computer and use it in GitHub Desktop.
Refarral users with level

1. User have multiple refer users and each of refer users have multiple refer users as like Tree

Like:

Screenshot 2024-07-24 at 9 14 03 PM

2. User Model:

    public $allusers = [];
    
    public function referral(){
        return $this->belongsTo(User::class, 'referral_id');
    }
    
    public function referralUsers($id, $currentLevel = 1){
        $users = $this->getUsers($id);
        if ($users['status']) {
            $this->allusers[$currentLevel] = $users['user'];
            $currentLevel++;
            $this->referralUsers($users['ids'], $currentLevel);
        }
        return $this->allusers;
    }
    
    public function scopeLevel()
    {
        $count = 0;
        $user_id = $this->id;
        while ($user_id != null) {
            $user = User::where('referral_id', $user_id)->first();
            if (!$user) {
                break;
            } else {
                $user_id = $user->id;
                $count++;
            }
        }
        return $count;
    }
    
    public function getUsers($id)
    {
        if (isset($id)) {
            $data['user'] = User::whereIn('referral_id', $id)->get(['id', 'firstname', 'lastname', 'username', 'email', 'phone_code', 'phone', 'referral_id', 'created_at']);
            if (count($data['user']) > 0) {
                $data['status'] = true;
                $data['ids'] = $data['user']->pluck('id');
                return $data;
            }
        }
        $data['status'] = false;
        return $data;
    }

3. Helper Function:

function getLevelUser($id){
    $ussss = new \App\Models\User();
    return $ussss->referralUsers([$id]);
}

4. Call Helper Function

return getLevelUser($id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment