Laravel - 模型启动创建不激活

时间:2016-03-10 04:32:14

标签: laravel laravel-5.2

我希望在$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';
        });
    }
}

我做错了什么?

1 个答案:

答案 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