引入模型观察者后,模型观察者中设置
public bool $afterCommit = true;
在提交所有事务后处理事件后报错,改为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
{
/**
* 在提交所有事务后处理事件
*
* @var bool
*/
public bool $afterCommit = true; //注:设置true后报错
public function creating(User $user): void
{
$user->nickname = substr_replace($user->mobile, '****', 3, 4);
$avatars = config('avatar');
$user->avatar = $avatars[array_rand($avatars)];
}
/**
* 处理用户「创建」事件。
*/
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
系统:macOS 14.2.1 与 debian_11_9_x64
引入composer包如下图:
我现在 illuminate/database illuminate/events 10.47 根本就不触发 模型事件 protected static function booted(): void
{
//创建模型之前执行
static::creating(function ($model) {
queueSend('ceshi',['a' => 'creating']);
echo 'creating';
//dump($model);
});
//创建模型之后执行
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);
});