[英]laravel model event from trait not firing
why this is not working??为什么这不起作用?? anything else i need to doo???还有什么我需要做的吗??? (note: i don't want to call any boot
method from model
). (注意:我不想从model
调用任何boot
方法)。 in models its working fine with booted
method在模型中它与booted
方法一起工作正常
// route
Route::get('/tests', function () {
return Test::find(1)->update([
'name' => Str::random(6)
]);
});
// models
namespace App\Models;
use App\Http\Traits\Sortable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
use HasFactory;
use Sortable;
protected $guarded = ["id"];
}
// traits
namespace App\Http\Traits;
trait Sortable
{
protected static function bootSort()
{
static::updated(function ($model) {
dd("updated", $model->toArray());
});
static::updating(function ($model) {
dd("updating", $model->toArray());
});
static::saving(function ($model) {
dd("saving", $model->toArray());
});
static::saved(function ($model) {
dd("saved", $model->toArray());
});
}
}
I got the answer if I want to fire model event from trait: I have to make the boot method name as trait class name with prefix boot
如果我想从 trait 触发 model 事件,我得到了答案:我必须将引导方法名称设置为带有前缀boot
的 trait class 名称
for example: if my trait name is Sortable
the boot method name will be bootSortable
below is the full solution to question:例如:如果我的特征名称是Sortable
,则引导方法名称将是bootSortable
下面是问题的完整解决方案:
// route
Route::get('/tests', function () {
return Test::find(1)->update([
'name' => Str::random(6)
]);
});
// models
namespace App\Models;
use App\Http\Traits\Sortable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
use HasFactory;
use Sortable;
protected $guarded = ["id"];
}
// traits
namespace App\Http\Traits;
trait Sortable
{
// before
protected static function bootSort()
// after fix
protected static function bootSortable()
{
static::updated(function ($model) {
dd("updated", $model->toArray());
});
static::updating(function ($model) {
dd("updating", $model->toArray());
});
static::saving(function ($model) {
dd("saving", $model->toArray());
});
static::saved(function ($model) {
dd("saved", $model->toArray());
});
}
}
you can use laravel observers , it's much more simpler你可以使用laravel observers ,它更简单
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.