我希望在$protected $foo
事件中为'foo'
分配static::creating
,但是当我输出最终对象时,该属性为null。事件似乎没有发生:
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';
});
}
}
我做错了什么?
答案 0 :(得分:4)
你的代码工作正常,我以这种方式测试了我的结尾
在模型中
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";
});
}
控制器中的
AccountCreation::create(['by'=>'as','to'=>'fff','hash'=>'aasss']);
在浏览器中获得此回复
successfully fired
fooasdfasdfad =====
successfully fired created