Skip to content
Advertisement

Laravel: withCount auth()->user() relationship

I my laravel (7.x) application. I have to models User and UserReferral with hasMany relationships.

User.php

class User extends Authenticate implements MustVerifyEmail
{
    public function referrals()
    {
        return $this
            ->hasMany(UserReferral::class)
            ->orderBy('created_at', 'DESC')
            ->skip(0)
            ->take(10);
    }
}

UserReferral.php

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

The list of Referrals has load-more pagination, total number of records and number of pages.

I need to get the total number of records to calculate the total number of pages.

I have already tried this auth()->user()->withCount('referrals') but it doesn’t work.

Advertisement

Answer

I have already tried this auth()->user()->withCount('referrals') but it doesn’t work.

Try to add the ->get(); at the end.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement