Order by count this month

Posted 9 months ago by ralphmorris

Hi there,

I have a referral system where users can refer other users.


    public function referredBy()
        return $this->belongsTo('App\User', 'referred_by');

    public function referrals()
        return $this->hasMany('App\User', 'referred_by');

There is also a 'referral_activated' dateTime field which gets set once the user is confirmed which is the point when the referrer gets their reward.

In our admin interface I am trying to get the top 3 referrers this month and order them by their referrals count that month.

My code so far.

    // Controller
    public function topReferrersThisMonth()
        return User::whereHas('referrals', function ($query) {
                    ->orderBy('referrals_count', 'desc')

    // Model
    public function scopeThisMonth($query, $field = 'created_at')
        return $query
            ->whereDate($field, '>=', Carbon::now()->startOfMonth())
            ->whereDate($field, '<=', Carbon::now()->endOfMonth());

This almost does what I want apart from it is ordering by the total count, not the count this month. Can anyone point me in the right direction?

Thanks :)


Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.