fill($request->input()); $payment->save(); if($request->input('invoices')) { $invoices = Invoice::whereIn('id', array_column($request->input('invoices'),'id'))->company()->get(); $payment->invoices()->saveMany($invoices); foreach($request->input('invoices') as $paid_invoice) { $invoice = Invoice::whereId($paid_invoice['id'])->company()->first(); if($invoice) ApplyInvoicePayment::dispatchNow($invoice, $payment, $paid_invoice['amount'], $invoice->company); } } else { //paid is made, but not to any invoice, therefore we are applying the payment to the clients credit ApplyClientPayment::dispatchNow($payment, $payment->company); } event(new PaymentWasCreated($payment, $payment->company)); //UpdateInvoicePayment::dispatchNow($payment); return $payment->fresh(); } }