with(['user', 'cabang'])->get(); // Initialize an empty array to hold the used budget sums $usedBudget = []; foreach ($budget as $b) { // Get the month and year from the budget $month = $b->periode_month; $year = $b->periode_year; // Add the used budget per model for the specified month and year to the usedBudget array $usedBudget[] = [ 'FormUpCountry' => FormUpCountry::whereIn('status', ['Approved', 'Closed']) ->whereMonth('tanggal', '=', date('m', strtotime($month))) ->whereYear('tanggal', '=', $year) ->sum('approved_total'), 'FormMeetingSeminar' => FormMeetingSeminar::whereIn('status', ['Approved', 'Closed']) ->whereMonth('created_at', '=', date('m', strtotime($month))) ->whereYear('created_at', '=', $year) ->sum('approved_total'), 'FormOthers' => FormOthers::whereIn('status', ['Approved', 'Closed']) ->whereMonth('tanggal', '=', date('m', strtotime($month))) ->whereYear('tanggal', '=', $year) ->sum('approved_total'), 'FormEntertaimentPresentation' => FormEntertaimentPresentation::whereIn('status', ['Approved', 'Closed']) ->whereMonth('tanggal', '=', date('m', strtotime($month))) ->whereYear('tanggal', '=', $year) ->sum('approved_total'), 'FormVehicleRunningCost' => FormVehicleRunningCost::whereIn('status', ['Approved', 'Closed']) ->whereMonth('tanggal', '=', date('m', strtotime($month))) ->whereYear('tanggal', '=', $year) ->sum('approved_total') ]; } $usedBudget = array_sum(array_map(function ($b) { return array_sum($b); }, $usedBudget)); $availableBudget = $budget->sum('amount') - $usedBudget; return $availableBudget; } }