mahbubrn's avatar

How to group by "year" list data into 12 months

here is my code -

$list  = Balance::whereYear('date', $this->year)->get();

i want to divide "year" list data into 12 months by eloquent methods like "GroupBY()" or anything. thanks.

0 likes
9 replies
mahbubrn's avatar

@jlrdw What I want is not there. I want all row list as month name or number.

tykus's avatar

@mahbubrn do you want data only for the current year, or for the 12 months up to the current date?

2 likes
mahbubrn's avatar

@tykus current year or any other year which i will provide. i mean when i will provide any year like 2023 / 2022 / 2021 this will show me 12 months data list.

example -

month: jan
list: row lists of january
month: feb
list: row list of february. 
tykus's avatar

@mahbubrn and should the resulting data for January, February, etc. should be an aggregation of one of the table columns?

2 likes
mahbubrn's avatar

@tykus i only need row list as months. then i will work with those lists what i want. manually i wrote the code this way -

$a = [];
$b = Balance::whereNotNull('date')->whereYear('date', 2023)->get();
foreach($b as $item)
{
    $month = explode('-', $item->date)[1]; // date: Y-m-d
    if(!isset($a[$month]))
    {
        $a[$month] = [$item];
    }
    else
    {
        $a[$month][] = $item;
    }
}

return $a;
tykus's avatar
tykus
Best Answer
Level 104

@mahbubrn since I now understand what you needed... you can use a Collection groupBy method like this.

$a = Balance::whereNotNull('date')->whereYear('date', 2023)->get() // your original query
    ->groupBy(fn($item) => \Carbon\Carbon::parse($item->date)->month) 
2 likes
DhPandya's avatar

@mahbubrn

$list  = Balance::whereYear('date', $this->year)->groupByRaw('YEAR(date)')->get();
1 like
MohamedTammam's avatar

If you want to have groups of each month, then after fetching them you can use groupBy collection method.

$list  = Balance::whereYear('date', $this->year)->get();
$grouped = $list->groupBy(function (array $item, int $key) {
    return $item->date->month;
});
1 like

Please or to participate in this conversation.