我创建了一个观察者,以便在创建/更新/删除事务时执行某些操作。
它适用于创建/删除方法,但由于某种原因,更新和更新的方法不会被触发。
这是我的观察员:
<?php
namespace App\Observers\Finance;
use App\Finance\Account;
use App\Finance\Transaction;
use Illuminate\Contracts\Queue\ShouldQueue;
class TransactionObserver implements ShouldQueue
{
/**
* The name of the queue the job should be sent to.
*
* @var string|null
*/
public $queue = 'transactions';
/**
* Updates account balance
*
* @param Account $Account
* @param int $amount
* @param int $old_amount
*/
public function updateAccountBalance(Account $Account, $amount = 0, $old_amount = 0)
{
$newBalance = $Account->balance - ($old_amount * 100) + ($amount * 100);
$Account->update(['balance' => $newBalance]);
}
/**
* Listen to the Transaction created event.
*
* @param Transaction $Transaction
* @return void
*/
public function created(Transaction $Transaction)
{
$this->updateAccountBalance($Transaction->account, $Transaction->amount);
}
/**
* Listen to the Transaction updating event.
*
* @param Transaction $Transaction
* @return void
*/
public function updating(Transaction $Transaction)
{
$this->updateAccountBalance($Transaction->account, 0, $Transaction->amount);
}
/**
* Listen to the Transaction updated event.
*
* @param Transaction $Transaction
* @return void
*/
public function updated(Transaction $Transaction)
{
$this->updateAccountBalance($Transaction->account, $Transaction->amount);
}
/**
* Listen to the Transaction deleted event.
*
* @param Transaction $Transaction
* @return void
*/
public function deleting(Transaction $Transaction)
{
$this->updateAccountBalance($Transaction->account, 0, $Transaction->amount);
}
}
和控制器中的更新方法:
public function update(Request $request, Transaction $transaction)
{
if (in_array($transaction->id, Transaction::$nonEditable)) {
abort(404);
}
$this->validate($request, [
'title' => 'required|max:255',
'account_id' => 'required|exists:accounts,id',
'season_year' => 'required|integer|exists:seasons,year',
'finance_category_id' => 'required|integer|exists:finance_categories,id',
'amount' => 'numeric',
'date' => 'required|date_format:d/m/Y',
]);
$transaction->update($request->all());;
flash()->success('האובייקט עודכן בהצלחה');
return redirect()->route('transactions.index');
}
我做错了什么? 另外,ShouldQueue是否与观察员合作?