Reputation: 922
how can I sort posts by vote counts in Laravel? If I have this kind of tables:
posts table
id, post_name, post_description
votes table
id, post_id, user_id
I want to sort posts by most votes.
Upvotes: 1
Views: 309
Reputation: 9649
If you declared your relationships correctly, i guess sth. like that should work:
$sortedposts= Post::with('votes')->get()->sortBy(function($post)
{
return $post->votes->count();
});
Upvotes: 1