public function monthlyExpenses(Request $request, $month = null) { $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; $otherMonth = isset($month) && ($month > 0 && $month < 13); $currentMonthTrackedExpenses = TrackedExpenses::query(); if ($otherMonth) { //Get a Specific Months Data $monthStart = Carbon::create(date('Y'), $month, 1, 0, 0, 0); $monthEnd = Carbon::create(date('Y'), $month, 1, 0, 0, 0)->endOfMonth(); $currentMonthTrackedExpenses = $currentMonthTrackedExpenses->where('created_at', '>=', $monthStart)->where('created_at', '<=', $monthEnd); if ($month == 1) { $monthStart = clone $monthStart; $monthStart->previous()->startOfMonth(); $monthEnd = clone $monthEnd; $monthEnd = $monthEnd->firstOfMonth()->previous()->endOfMonth(); } else { $monthStart = $monthStart->previous()->startOfMonth(); $monthEnd = $monthEnd->previous()->lastOfMonth(); } $lastMonthData = TrackedExpenses::where('created_at', '>=', $monthStart)->where('created_at', '<=', $monthEnd)->orderBy('id', 'asc')->get()->toArray(); } else { //Get current Months Data $currentMonthTrackedExpenses = $currentMonthTrackedExpenses->where('created_at', '>=', Carbon::now()->startOfMonth())->where('created_at', '<=', Carbon::now()->endOfMonth()); $lastMonthData = TrackedExpenses::where('created_at', '>=', Carbon::now()->startOfMonth()->previous()->firstOfMonth())->where('created_at', '<=', Carbon::now()->startOfMonth()->previous()->lastOfMonth())->get()->toArray(); } //$lastMonthData = $lastMonthData->orderBy('id','desc')->get()->toArray(); $currentMonthTrackedExpenses = $currentMonthTrackedExpenses->orderBy('id', 'desc')->get(); $expenses = Expense::where('active', 1)->get(); $current = 0; foreach ($expenses as $expense) { $e[$current]['expense'] = $expense; $e[$current]['monthlypayed'] = $this->findExpense($expense->id, $currentMonthTrackedExpenses); $e[$current]['lastMonthCost'] = $this->findExpenseLastMonth($expense->id, $lastMonthData); $current++; } return ['month' => $otherMonth ? $months[$month - 1] : Date('F'), 'payments' => $e, 'year' => date('Y')]; }