Last active
December 20, 2021 15:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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