bsa*_*aka 5 laravel laravel-5.2
我想在事件中$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';
});
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Qaz*_*azi 10
您的代码运行良好,我以这种方式在最后进行了测试
在模型中
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";
});
}
Run Code Online (Sandbox Code Playgroud)
在控制器中
AccountCreation::create(['by'=>'as','to'=>'fff','hash'=>'aasss']);
Run Code Online (Sandbox Code Playgroud)
在浏览器中,得到这个响应
successfully fired
fooasdfasdfad =====
successfully fired created
Run Code Online (Sandbox Code Playgroud)