Question

According to http://laravel.com/docs/eloquent#model-observers the following events are being fired when creating a new item. creating then created then saving then saved.

However when I do call a model class, the events are being fired the other way round. Saving is called before creating.

My Code:

class TBone extends Eloquent {

    protected $table = 'bone';

    protected $primaryKey = 'id';

    protected $guarded = array('id');

}

The Observer Class:

class ObserverLeBone{

    public function creating($bone)
    {
        echo "creating\r\n";
    }

    public function saving($bone) 
    {
        echo "saving\r\n";
    }

    public function updating($bone) 
    {
        echo "updating\r\n";
    }
}

The Test:

class EloquentTest extends TestCase {

    public function testObserver()
    {
       TBone::observe(new ObserverLeBone());
       $attributes = array('appreciatedAs' => 'Steak'); 
       TBone::create($attributes);
    }

}

Output when running the Test Case:

saving
creating

So I am just wondering why the saving event is fired before the creating event? Or am I missing something ?

Was it helpful?

Solution

Not sure if it's a bug or feature, but you are right, according to the code, create calls save:

public static function create(array $attributes)
{
    $model = new static($attributes);

    $model->save();

    return $model;
}

And save fire the event:

public function save(array $options = array())
{
    $query = $this->newQueryWithDeleted();

    // If the "saving" event returns false we'll bail out of the save and return
    // false, indicating that the save failed. This gives an opportunities to
    // listeners to cancel save operations if validations fail or whatever.
    if ($this->fireModelEvent('saving') === false)
    {
        return false;
    }

            ....

Before performing insert (create):

    else
    {
        $saved = $this->performInsert($query);
    }

Which fires the creating event

if ($this->fireModelEvent('creating') === false) return false;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top