user3569641
user3569641

Reputation: 922

Sorting post by vote counts in Laravel

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

Answers (1)

nozzleman
nozzleman

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

Related Questions