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.
@jlrdw What I want is not there. I want all row list as month name or number.
@mahbubrn do you want data only for the current year, or for the 12 months up to the current date?
@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.
@mahbubrn and should the resulting data for January, February, etc. should be an aggregation of one of the table columns?
@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;
@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)
@mahbubrn
$list = Balance::whereYear('date', $this->year)->groupByRaw('YEAR(date)')->get();
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;
});
Please sign in or create an account to participate in this conversation.