I am trying to sum up the total values for each month in a year but cannot do it correctly, it fetch the first value of each month and not the others.
$wastes = WasteCategory::with(['logReport' => function($log) use ($year) {
$log->whereYear('sanitation_date_time', $year);
}])->get();
$months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
$allTotal = [];
foreach ($wastes as $waste) {
foreach ($months as $month) {
if (!array_key_exists($month, $allTotal)) {
foreach ($waste->logReport as $log) {
$logMonth = date('m', strtotime($log->sanitation_date_time));
$sum = $log->where('waste_category', $waste->waste_category_name)->whereMonth('sanitation_date_time', $month)->sum('waste_weight');
if ($logMonth == $month) {
$allTotal[$month] = [
$waste->waste_category_name => isset($allTotal[$month]) && !array_key_exists($waste->waste_category_name, $allTotal[$month]) ? $sum : 0
];
}
}
} else {
foreach ($waste->logReport as $log) {
$logMonth = date('m', strtotime($log->sanitation_date_time));
if ($logMonth == $month) {
$allTotal[$month] = $log->where('waste_category', $waste->waste_category_name)->whereMonth('sanitation_date_time', $month)->sum('waste_weight');
}
}
}
}
}
What did I do wrong?