skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 be bootSortable below is the full solution to question:

    // 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
    {
        // 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());
            });
        }
    }
    

  2. you can use laravel observers, it’s much more simpler

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search