Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

closer01's avatar

How to sort likes from controller

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 ?

0 likes
6 replies
edoc's avatar
edoc
Best Answer
Level 24

Here u go

Post::withCount('likes')->orderBy('likes_count', 'desc')->get()
1 like
jekinney's avatar

Post::withCount('likes')->orderBy('likes_count', 'asc')->get();

The withCount adds the likes_count data to the post collection.

1 like

Please or to participate in this conversation.