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

Mav23Sa's avatar

how to get the most used categories of my site

This is my DB

POSTS id, title, .. .., category_id

CATEGORIES id, title, .. ..

my post model have a relation

public function category()
    {
        return $this->belongsTo(Categories::class, 'category_id');
    }

i need to get the top 5 categories used in my posts tables how can i do this with eloquent

0 likes
3 replies
MichalOravec's avatar
$categories = Category::withCount('posts')->orderByDesc('posts_count')->limit(5)->get();

Please for model always use singular form.

So Category model has to have hasMany relationship posts().

Mav23Sa's avatar

oooohhhh I was doing it wrong. I tried to count the categories from the post method

Thank you.

Please or to participate in this conversation.