JillzTom's avatar

Sort user based on followers count

I'm trying to sort users based on the followers count. I've a polymorphic relation to store the followers.

//To get the followers
$user->followers

and I'm trying to find the users with most followers and sort it with pagination. How do I go about it?

0 likes
3 replies
joedawson's avatar
Level 18

I used something like this once to order Photos by their number of views.

$photos = Photo::leftJoin('views','photos.id','=','views.photo_id')->
                selectRaw('photos.*, count(views.photo_id) AS `count`')->
                groupBy('photos.id')->
                orderBy('count', 'DESC')->
                get();

Maybe just replace Photo with User and the views with followers? This may work?

$users = User::leftJoin('followers','users.id','=','followers.user_id')->
                selectRaw('users.*, count(followers.user_id) AS `count`')->
                groupBy('users.id')->
                orderBy('count', 'DESC')->
                get();
2 likes
JillzTom's avatar

@JoeDawson for some reason, it's not fetching all the users. My table structure for followers is as below:

// Like model - table name "likes"
user_id (uuid)
likeable_id (uuid)
likeable_type (string) For followers, it will be 'App\User'

Please or to participate in this conversation.