Skip to content
Advertisement

How to use groupBy() to group a Collection object

My goal is to retrieve all of a user’s ‘items’ and display then in my view grouped by their ‘status’. There are 4 possible statuses, each with their own <div> on the page containing the items’ info. After some poking around I believe I need to use the groupBy() method like so:

$items = Item::ownedBy( Auth::id() )->groupBy('status')->get();

This does seem to do some sort of grouping, but when I iterate over the collection I get a max of 4 results, one for each status. This doesn’t really solve my problem as I need to display all of a user’s items for each status, not just one. I must be missing something here, I’d really like to avoid making a query for each status and displaying them that way. I suppose I could filter the collection by status and create 4 new collections, but isn’t this what groupBy() is supposed to do?

Advertisement

Answer

You can do that very easy with laravel and Collections. Collections have powerful API and a lot of handy methods, to easily achieve what you want.

Your mistake here is that you are calling groupBy on the QueryBuilder object which returns only groupped by records from the database. Instead you must select all of the records you need, then they will be returned as a collection. After that you can manipulate the collection as you wish. So what you need is:

$items = Item::ownedBy( Auth::id() )->get()->groupBy('status');

You can view all of the Colletion class useful methods here.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement