Laravel Users with posts count

Edward Ziadeh • 26 February 2019
Blog in group Laravel
0 comments
0 likes

How to create a list of users with all posts count, what that mean

I have a list of users
 

ID Name
1 Edd
2 Robert

 

List of posts

id user_id title body created_at
1 1 title 1 body 1 22/2/2019
2 1 title 2 body 2 23/2/2019
3 1 title 3 body 3 22/2/2019
4 2 title 4 body 4 21/2/2019

 

The result should look like this: count all posts for each user and sort by count.

user_id username count
1 Edd 3
2 Robert 1

 


$usersWithMostPosts = Post::with('user')->whereBetween('created_at', [$from, $to])->groupBy('user_id')->orderBy('count', 'DESC')->paginate(30, [
            DB::raw('user_id as "user_id"'),
            DB::raw('COUNT( * ) as "count"')
        ]);