我有付款模式,想在付款确认后触发自定义事件。
我的型号代码:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
protected $dates = [
'created_at', 'updated_at', 'confirmed_at',
];
public function confirmed(){
$this->setAttribute('confirmed_at', now());
$this->setAttribute('status', 'confirmed');
}
}
最佳答案
我可以开火 confirmed
事件在 Payment->confirmed()
方法,像这样:
public function confirmed(){
// todo, throw an exception if already confirmed
$this->setAttribute('confirmed_at', now());
$this->setAttribute('status', 'confirmed');
// fire custom event
$this->fireModelEvent('confirmed');
}
并将自定义事件注册到
$dispatchesEvents
protected $dispatchesEvents = [
'confirmed' => \App\Events\Payment\ConfirmedEvent::class
];
完毕。
\App\Events\Payment\ConfirmedEvent::class
事件将在模型 confirmed()
时调用方法被调用。如果confirmed() 方法被调用两次,它也建议抛出一个异常。
关于laravel - 如何将自定义事件添加到 Laravel 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363375/