Hardist
Hardist

Reputation: 1983

Laravel collection group by

I have a search function to search for expenses by a certain date, month, string, whatever. It returns a collection:

enter image description here

So far so good. I can display all returned Expenses. Now, what I want to do is, display also a total expense count and total amount, grouped by the description_id. If I simply do $result->groupBy('description_id), I just get a set of collections, from which I can display the total count and total amount, but not the name of the description. Example of what I want:

Grouped Results (By Expense):

Description Name: <-- Issue displaying this
Total Expenses: 3
Total Amount: 53444

The description name can only be obtained via the relation between Expense and Description. An Expense belongsTo a description.

Is it at all possible to achieve what I want, when working with my collection, or should I perform a seperate query for those results? (undesired)

Upvotes: 15

Views: 65724

Answers (1)

omitobi
omitobi

Reputation: 7334

If you eager-load description, then you can group the resulting collection by the nested object of the collection. So you may have:

$expenses = Expenses::with('description')->get(); //collection

Then group it:

$grouped = $expenses->groupBy('description.name'); 
//or
$grouped = $expenses->groupBy('description_id'); 

Then you can use the name of description, accessing it, say we need the first group, and the first expense in the group,

$description_name = $grouped
                    ->first() //the first group
                    ->first() //the first expense in group
                    ->description //the description object
                    ->name //the name

This is just a little proof that you can get the name of the related model in the collection and use it to solve your question.

Upvotes: 35

Related Questions