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

viraj's avatar
Level 11

Query to group by alphabet & also get total count and group count

I have a table for categories. I want to group each category by alphabet. I want to get count of each group as well as total number of categories. Would be nice if I can achieve this in one query.

Thanks

0 likes
1 reply
viraj's avatar
Level 11

Right now, the solution I came up with.

// In controller

$results = Category::all()->sortBy('name')->groupBy(function ($item, $key) {
    return substr($item['name'], 0, 1);
});



// In view - total count
{{ count($results->collapse()->all()) }}


// In view -individual count
@foreach($results as $key => $result)
    <h4>{{ ucfirst($key) }} - {{ count($result) }}</h4>
    // ul and other stuff ...
@endforeach
                            

Let me know if there any better way to do it.

Please or to participate in this conversation.