whereYear('date', '=', $year) ->orderBy('date') ->get() ->groupBy(function($item) { return Carbon::parse($item->date)->format('n'); }); $sums = array(); $startBalance = SubBooking::balanceAt($year - 1 . '-12-31'); $sums[0]['balance'] = $startBalance; $expeditures = SubBooking::expedituresInInterval( $year . '-01-01', $year . '-12-31', true); $incomes = SubBooking::incomesInInterval( $year . '-01-01', $year . '-12-31', true); // Create an array with the following properties: // 'balance' - The account balance at the last day of a month // 'expeditures' - the sum of all expeditures in this month // 'incomes' - the sum of all incomes in this month plus the account // balance of the previous month for ($month = 1; $month <= 12; $month++) { $sums[$month]['expeditures'] = $expeditures->where('month', '=', $month)->first()->expeditures; $sums[$month]['incomes'] = $expeditures->where('month', '<', $month)->sum('expeditures') + $incomes->where('month', '<=', $month)->sum('incomes') + $startBalance; $sums[$month]['balance'] = $sums[$month]['expeditures'] + $sums[$month]['incomes']; } return view('bookings.index', compact('bookings', 'year', 'sums')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function show(Booking $booking) { // } /** * Show the form for editing the specified resource. * * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function edit(Booking $booking) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function update(Request $request, Booking $booking) { // } /** * Show the dialog for deleting the specified resource. * * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function delete(Booking $booking) { // } /** * Remove the specified resource from storage. * * @param \App\Booking $booking * @return \Illuminate\Http\Response */ public function destroy(Booking $booking) { // } }