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.
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();