1

I want to sort all my users by the number of their posts. Like:

User1(100 posts)
User2(90 posts)
User3(80 posts)

How can I do this in laravel elequont relationship.

3 Answers 3

4

Use withCount to get the posts count without loading the relationship and sort the result using posts_count. You can also apply additional conditions if required. As a bonus you get the posts count with each user.

$users = User::withCount('posts')
    ->orderBy('posts_count', 'desc')
    ->get();
Sign up to request clarification or add additional context in comments.

Comments

1

Try this :

$data = User::select(DB::raw('users.*, count(*) as total_posts'))
    ->join('posts', 'users.id', '=', 'posts.user_id')
    ->groupBy('user_id')
    ->orderBy('total_posts', 'desc')
    ->get();

Comments

0

You can do it like this :

$users = User::with('posts')->get()-
>sortBy(function($users)
{
return $users->posts->count();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.