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

maaz's avatar
Level 2

How to query popular Posts/Category in laravel ?

How to Query popular categories using the eloquent model. I have a category model and showing popular categories on view. Do i need to created most_viewed or something like that column inside my model ?

note: I want to show only 4 categories. Ask for code if you need Thankyou :)

0 likes
7 replies
MichalOravec's avatar
Level 75

You need to add visits to your categories table

$mostPopularCategories = Category::orderByDesc('visits')->limit(4)->get();
1 like
maaz's avatar
Level 2

i don't have popularity field in my categories table

MichalOravec's avatar

It doesn't matter how you name it. It couls be hits, popularity, visits etc. You need to everytime increment that column when you visit that page.

maaz's avatar
Level 2

How I can implement this is there any helper method or something else which will track user when he visit the specific category,

maaz's avatar
Level 2

@michaloravec I thought it would be a bit tricky but that's so easy 😁 Btw Thank you so much dear 😍 it helps me a lot.

Please or to participate in this conversation.