Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Model boot creating not firing

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:

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?

like image 903
brietsparks Avatar asked Mar 10 '16 04:03

brietsparks


1 Answers

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
like image 127
Qazi Avatar answered Oct 07 '22 21:10

Qazi