- 从数据库检索现有模型时触发
retrieved
事件 - 模型第一次被保存时触发
creating
和created
事件 - 数据库中已存在此模型,并调用
save
方法,updating
/updated
事件会被触发 - 2和3都会触发
saving
/saved
事件 - 删除模型触发
deleting
,deleted事件
软删除恢复时触发restoring
,restored事件
public static function boot()
{
parent::boot();
static::retrieved(function ($model) {
Log::info('执行retrieved');
});
static::creating(function ($model) {
Log::info('执行creating');
});
static::created(function ($model) {
Log::info('执行created');
});
static::updating(function($model) {
Log::info('执行updating');
});
static::updated(function($model) {
Log::info('执行updated');
});
static::saving(function($model) {
Log::info('执行saving');
});
static::saved(function($model) {
Log::info('执行saved ');
});
static::deleting(function($model) {
Log::info('执行deleting ');
});
static::deleted(function($model) {
Log::info('执行deleted ');
});
static::restoring(function($model) {
Log::info('执行restoring ');
});
static::restored(function($model) {
Log::info('执行restored ');
});
}
自定义模型事件
//模型的操作=>自定义的事件类
protected $dispatchesEvents = [
'saving' => DynamicSavingEvent::class,
];
- 先创建event文件
<?php
namespace App\Event;
use NarutoBear\Dynamic\Model\PersonDynamic;
class DynamicSavingEvent
{
public $dynamic;
public function __construct(PersonDynamic $dynamic)
{
$this->dynamic = $dynamic;
}
}
- 在创建listenter文件
<?php
namespace App\Listeners;
use App\Event\DynamicSavingEvent;
class DynamicSaving
{
public function handle(DynamicSavingEvent $event)
{
app('log')->info($event->dynamic);
return false;//返回false,会阻止该条数据的更新
}
}
- 在eventserviceprovider注册监听器
protected $listen = [
DynamicSavingEvent::class => [
DynamicSaving::class
]
];
- 上面阻止更新的原因如下
public function save(array $options = [])
{
$query = $this->newModelQuery();
// If the "saving" event returns false we'll bail out of the save and return
// false, indicating that the save failed. This provides a chance for any
// listeners to cancel save operations if validations fail or whatever.
if ($this->fireModelEvent('saving') === false) {
return false;
}