Usually a balance is a derived column. A running total. But can be hard coded. If displaying elsewhere use the aggregate function SUM to show totals.
Mar 17, 2022
8
Level 10
How to update a field in another table when creating a model
Hi all,
I have two tables in a database: Account & Transactions. I have all the relations setup right.
When I create a transaction, let's say "Withdarw" money from the account, I want the account balance to be updated with the new value (transaction amount minus balance).
Here is what I have in my livewire controller:
public function transactionData()
{
return [
'item' => $this->item,
'amount' => $this->amount,
'type' => $this->type,
'account_id' => $this->account,
];
}
public function create()
{
$this->validate();
$transaction = Transaction::create($this->transactionData());
}
How do I update the account model with the new balance?
Any help is highly appreciated
Level 29
You have several ways to perform that.
- In the same function. I assume you have setup the correct relationship
public function create()
{
$this->validate();
$transaction = Transaction::create($this->transactionData());
$transaction->account()->decrement('balance', $amount);
}
- By using the eloquent events, ref: https://laravel.com/docs/9.x/eloquent#events
1 like
Please or to participate in this conversation.