validated(),'invoices') as $k=>$v) $o->{$k} = $v; foreach ($request->validated('invoices',[]) as $id => $amount) { // See if we already have a payment item that we need to update $items = $o->items ->filter(fn($item)=>$item->invoice_id == $id); if ($items->count() === 1) { $oo = $items->pop(); if ($amount == 0) { $oo->delete(); continue; } } else { $oo = new PaymentItem; $oo->invoice_id = $id; } $oo->amount = ($oo->invoice->due >= 0) && ($oo->invoice->due-$amount >= 0) ? $amount : 0; // If the amount is empty, ignore it. if (! $oo->amount) continue; $oo->site_id = config('site')->site_id; $oo->active = TRUE; $o->items->push($oo); } try { $o->pushNew(); } catch (\Exception $e) { return redirect() ->back() ->withErrors($e->getMessage())->withInput(); } return $o->wasRecentlyCreated ? redirect() ->to('r/payment/'.$o->id) ->with('success','Payment added') : redirect() ->back() ->with('success','Payment saved'); } }