Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel collection group by

Tags:

php

laravel

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)

like image 319
Hardist Avatar asked Jul 27 '17 19:07

Hardist


1 Answers

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.

like image 112
Oluwatobi Samuel Omisakin Avatar answered Sep 23 '22 00:09

Oluwatobi Samuel Omisakin