引入模型觀察者后,模型觀察者中設(shè)置
public bool $afterCommit = true;
在提交所有事務(wù)后處理事件后報錯,改為false即無錯誤。
laravel文檔地址:
https://learnku.com/docs/laravel/10.x/eloquent/14888#3bfe46
<?php
namespace app\observer;
use app\model\User;
use isszz\hashids\facade\Hashids;
class UserObserver
{
/**
* 在提交所有事務(wù)后處理事件
*
* @var bool
*/
public bool $afterCommit = true; //注:設(shè)置true后報錯
public function creating(User $user): void
{
$user->nickname = substr_replace($user->mobile, '****', 3, 4);
$avatars = config('avatar');
$user->avatar = $avatars[array_rand($avatars)];
}
/**
* 處理用戶「創(chuàng)建」事件。
*/
public function created(User $user): void
{
$user->hash_code = Hashids::mode('other')->encode($user->id);
$user->save();
$user->detail()->firstOrCreate();
}
}
controller代碼:
model代碼:
報錯信息:
版本:php 8.1
系統(tǒng):macOS 14.2.1 與 debian_11_9_x64
引入composer包如下圖:
之前illuminate/database和illuminate/events為8.0版本不會報錯
public bool $afterCommit = true;設(shè)置屬性后無效果
現(xiàn)在illuminate/database和illuminate/events升級到最新版$afterCommit = true后確實會報錯了
我現(xiàn)在 illuminate/database illuminate/events 10.47 根本就不觸發(fā) 模型事件 protected static function booted(): void
{
//創(chuàng)建模型之前執(zhí)行
static::creating(function ($model) {
queueSend('ceshi',['a' => 'creating']);
echo 'creating';
//dump($model);
});
//創(chuàng)建模型之后執(zhí)行
static::created(function ($model) {
echo 'created';
//dump($model);
});
//修改之前
static::updating(function (User $model) {
queueSend('ceshi',['a' => 'updating']);
echo 'updating';
//dump($model);
});
//修改之后
static::updated(function ($model) {
queueSend('ceshi',['a' => 'updated']);
echo 'updated';
//dump($model);
});
static::saving(function ($model) {
echo 'saving';
queueSend('ceshi',['a' => 'updated']);
//dump($model);
});
static::saved(function ($model) {
echo 'saved';
queueSend('ceshi',['a' => 'updated']);
//dump($model);
});
static::deleting(function ($model) {
echo 'deleting';
//dump($model);
});
static::deleted(function ($model) {
echo 'deleted';
//dump($model);
});
}完全不觸發(fā)