Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrisml's avatar

Ranking a user based on referrals

I'm trying to figure out how to get a ranking for a user in terms of friend signups.

For example, a user with the most referrals will be ranked #1.

I'm not sure where to start with queries. I currently have a referrals column in the users table which increments with each referral they make.

0 likes
7 replies
davidfaux's avatar
    User::orderBy('referrals')->get();

Could it be as easy as this?

chrisml's avatar

@dfaux: I want to get a ranking for a specific user. Is that possible?

davidfaux's avatar

Ok I am going to give this a shot using query builder, don't have access to a test environment so this is a stab in the dark :)

    $rank = DB::table('users')->select(DB::raw('count(*) as rank'))
        ->where('referrals', '>', function($query) use ($user)
        {
            $query->select('referrals')->from('users')->where('id', $user->id)
        })->first();

If this does work you might need to increment the rank, test if this is the case.

chrisml's avatar

@dfaux: Hm, doesn't seem to return the correct rank for a user. Just 0/1.

Woodlandtrek's avatar

So using the referral count on your users model, you can get the rank of the current user like this:

    public function getRankAttribute()
    {
        $count = \DB::table('users')->where('referrals', '>', $this->referrals)->count();
        return $count ? $count + 1 : NULL;
    }

With this on your model, you can get the rank with $user->rank

martinbean's avatar

@Woodlandtrek That really isn’t optimal, that’s going to execute an additional query for every user that comes back as part of a collection, or in simple terms: the N+1 problem.

Woodlandtrek's avatar

@martinbean yeah, I understand it's not good for large groups. @cml123 shared the context on IRC and was only going to be using it for individual records.

An accessor like that won't be called just because the parent object is returned in a collection, will it? Only if the method is called explicitly?

Please or to participate in this conversation.