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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:22:34  来源:igfitidea点击:

Laravel - Model boot creating not firing

laravellaravel-5.2

提问by bsapaka

I would like $protected $footo be assigned 'foo'in the static::creatingevent, 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