Thanks in advance for any help. I have an Invoice Model which has a one-to-many relationship with the payment model and when I loop through an invoice's payments to add all the $payment->net and subtract it from the $invoice->cost to see the balance that is left. The payment that was just made in the same call doesn't appear in $invoice->payments, it feels like its cached.
Invoice.php
public function payments()
{
return $this->hasMany('App\Payment');
}
public function net() :float
{
$payments = $this->payments;
$net = $this->cost;
foreach ($payments as $payment) {
$net += $payment->net;
}
return $net;
}
public function balance() :float
{
return ($this->cost - $this->net());
}
Payment.php
public function invoice()
{
return $this->belongsTo('App\Invoice');
}
PaymentController.php
$invoice = Invoice::findOrFail($id);
// Check ownership
if(!$this->getCurrentUser()->isSuperuser() && $this->getCurrentUser()->id === $invoice->user_id) {
throw new ModelNotFoundException();
}
$payment = new Payment($request->all());
$payment->ref = Payment::generateRef($invoice->id, $request->input('type'));
// Check for overpayment
if($invoice->balance() < $payment->net) {
throw new BadInputException('Payment exceeds balance.');
}
if($payment = $invoice->payments()->save($payment)) {
if($invoice->balance() == 0) {
$invoice->status = Invoice::CLOSED;
$invoice->save();
}
}
return $payment;