laravel Eloquent的模式事件

  1. 从数据库检索现有模型时触发 retrieved 事件
  2. 模型第一次被保存时触发creating 和 created事件
  3. 数据库中已存在此模型,并调用 save 方法,updating / updated 事件会被触发
  4. 2和3都会触发saving / saved 事件
  5. 删除模型触发deletingdeleted事件
  6. 软删除恢复时触发restoringrestored事件
    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;
    }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值