brietsparks
brietsparks

Reputation: 5006

Laravel set/modify Model attribute during trait boot

Is it possible for a trait's boot method to set or modify a Model's attribute? The following non-working example illustrates what I am going for:

trait MyTrait {

    public static function bootMyTrait(){
        static::creating(function(Model $item){
            $item->foo = 'foo';
        });
    }
}

Upvotes: 2

Views: 3315

Answers (2)

Igor
Igor

Reputation: 83

I know this threat is pretty old but this answer is for anyone who still needs to know:

In your trait set a static method called boot[YourTraitName].

trait MyTrait {
    public static function bootMyTrait(){
        static::saved(function(){ /*...*/ });
    }
}

Your model will trigger both its own boot method and the one declared in the traits.

Upvotes: 2

cresjie
cresjie

Reputation: 469

if your gonna set/modify attribute value automatically during creation, you can just override the boot method of the model

trait MyTrait {
   protected static function boot()
   {
      parent::boot();
      static::creating(function($model){
         $model->foo = 'foo';
      });
    }
}

Upvotes: 0

Related Questions