why this is not working?? anything else i need to doo??? (note: i don’t want to call any boot
method from model
). in models its working fine with booted
method
// route
Route::get('/tests', function () {
return Test::find(1)->update([
'name' => Str::random(6)
]);
});
// models
namespace AppModels;
use AppHttpTraitsSortable;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Test extends Model
{
use HasFactory;
use Sortable;
protected $guarded = ["id"];
}
// traits
namespace AppHttpTraits;
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());
});
}
}
2
Answers
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
for example: if my trait name is
Sortable
the boot method name will bebootSortable
below is the full solution to question:you can use laravel observers, it’s much more simpler