whereYear('loading_date', '=', '2021')->orderBy('loading_date')->get(); $total = 0; $customers = collect(); foreach ($containers as $container){ foreach($container->packingLists as $packingList){ $cbm = $packingList->packages->sum(function ($package){ return (( (float) $package->width / 100) * ( (float) $package->length / 100) * ( (float) $package->height / 100)) * $package->quantity; }); $total += $cbm; $marking = $packingList->owner->companyModule->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference; if(!$customers->has($marking)){ $customers->put($marking, collect([ 'cbm' => $cbm, 'orders' => 1, 'packages' => $packingList->packages->sum('quantity') ])); continue; } $customers[$marking]['cbm'] += $cbm; $customers[$marking]['orders'] += 1; $customers[$marking]['packages'] += $packingList->packages->sum('quantity'); } } $activeOrders = $customers->sum(function($customer){ return $customer['orders']; }); return (new ApiResponseObject('fetch monthly report Successful', '', HttpStatus::OK_WITH_MESSAGE, ['data' => [ 'containers' => count($containers), 'activated_orders' => $activeOrders, 'active_customers' => count($customers), 'total_cbm' => $customers->sum(function($customer){ return $customer['cbm']; }), 'packages' => $customers->sum(function($customer){ return $customer['packages']; }), 'total_orders' => Order::whereMonth('created_at', 9)->whereHas('packingLists')->count() ]]))->handler(); } }