Level 75
$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().
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
Please or to participate in this conversation.