Reputation: 5006
I would like $protected $foo
to be assigned 'foo'
in the static::creating
event, but when I output the final object, the property is null. The event does not seem to fire:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model {
protected $foo;
public static function boot() {
parent::boot();
static::creating(function (Item $item) {
echo "successfully fired"; //this does not get echoed
$item->foo = 'foo';
});
}
}
What am I doing wrong?
Upvotes: 9
Views: 37599
Reputation: 81
I used this code in laravel 9:
protected static function booted()
{
static::creating(function ($model) {
$model->code = self::generateUniqueCode();
});
}
Upvotes: 3
Reputation: 5135
Your code is working fine, I tested at my end in this way
In Model
protected $foo;
public static function boot() {
parent::boot();
//while creating/inserting item into db
static::creating(function (AccountCreation $item) {
echo "successfully fired";
$item->foo = 'fooasdfasdfad'; //assigning value
});
//once created/inserted successfully this method fired, so I tested foo
static::created(function (AccountCreation $item) {
echo "<br /> {$item->foo} ===== <br /> successfully fired created";
});
}
in Controller
AccountCreation::create(['by'=>'as','to'=>'fff','hash'=>'aasss']);
in browser, got this response
successfully fired
fooasdfasdfad =====
successfully fired created
Upvotes: 16