M
M
matros972020-06-26 10:21:33
Laravel
matros97, 2020-06-26 10:21:33

Laravel sort categories by number of entries?

Hello, help me solve this problem, there are categories with posts, you need to make it so that the categories that have posts are displayed and sorted by the number of entries, the
first I did, I display the categories that have entries

$categories = Category::has('projects')->with('projects')->get();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2020-06-26
@jazzus

$categories = Category::has('projects')
                      ->with('projects')
                      ->withCount('projects')
                      ->orderByDesc('projects_count')
                      ->get();

I
Ilya, 2020-06-26
@New_Horizons

$hackathons = Hackathon::with('participants')->get()->sortBy(function($hackathon)
{
    return $hackathon->participants->count();
});

Source: First link on google

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question