Laravel - 模型引导创建不触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35907641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - Model boot creating not firing
提问by bsapaka
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:
我想在事件中$protected $foo
赋值,但是当我输出最终对象时,该属性为空。该事件似乎没有触发:'foo'
static::creating
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?
我究竟做错了什么?
回答by Qazi
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