orderBy('created_at', 'desc')->with(['user', 'cabang'])->get(); // Initialize an empty array to hold the used budget sums $usedBudget = 0; 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 $users = UserHasCabang::where('cabang_id', $cabang_id)->get(); $userIds = $users->pluck('user_id')->toArray(); $forms = FormHelper::getFormsByUserIds($userIds, $month, $year)->sortByDesc('tanggal')->sortByDesc('created_at'); $usedBudget += $forms->sum('approved_total'); } $availableBudget = $budget->sum('amount') - $usedBudget; return $availableBudget; } }