Here u go
Post::withCount('likes')->orderBy('likes_count', 'desc')->get()
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi, I use post like system which use Many to Many Polymorphic Relationships , every thing works fine, but my problem is i want to sort descending from likes ...
I have posts and likeables tables in database
likeables table is like this :
id user_id post_id
1 1 1
2 2 1
3 3 1
4 1 2
5 2 2
So post 1 has 3 , post 2 has 2 likes...
How i can fetch and sort posts from controller from popular to less popular ?
Here u go
Post::withCount('likes')->orderBy('likes_count', 'desc')->get()
Please or to participate in this conversation.