Skip to content

Instantly share code, notes, and snippets.

@MACscr
Last active December 20, 2021 15:44
Show Gist options
  • Save MACscr/69dbedd992c6c2bfe54f295f28413698 to your computer and use it in GitHub Desktop.
Save MACscr/69dbedd992c6c2bfe54f295f28413698 to your computer and use it in GitHub Desktop.
Observer to watch transactions associated with an invoice and mark paid/unpaid if transaction sums meet invoice total.
<?php
....
class Transaction extends Model
{
.....
public function monitor_transaction()
{
$invoice = Invoice::find($this->invoice_id);
if ($invoice) {
$total_due = $invoice->total;
$sum = $invoice->transactions->sum('amount');
Log::debug('Sum: '.$sum);
if ($sum >= $total_due) {
$invoice->status = 'paid';
$invoice->save();
Log::debug('Marked as paid');
} else {
$invoice->status = 'unpaid';
$invoice->save();
Log::debug('Marked as unpaid');
}
}
}
}
<?php
namespace App\Observers;
use App\Models\Transaction;
class TransactionsToInvoice
{
/**
* Handle the Transaction "created" event.
*/
public function created(Transaction $transaction)
{
$transaction->monitor_transaction();
}
/**
* Handle the Transaction "updated" event.
*/
public function updated(Transaction $transaction)
{
$transaction->monitor_transaction();
}
/**
* Handle the Transaction "deleted" event.
*/
public function deleted(Transaction $transaction)
{
$transaction->monitor_transaction();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment