Framework: [4.2] Fail save on Eloquent model events created, updated, saved

Created on 28 Oct 2014  路  2Comments  路  Source: laravel/framework

I would like to have models fail a save if one of the created, updated or saved event handlers fails and returns false. Currently the model class assumes that once the actual creation in the database has taken place successfully the save will always be successful and therefore ignores whether any listener on the post creation events fails and just moves on silently. In my opinion this is bad design and I will explain my current use case which outlines why you should at least be able to set an option to make it fail, or in my opinion make it the default behaviour:

I have a model A which always has to have at least one Model B associated to it. In other words A has many but at least one B. B belongs to exactly one A.
To make things easy on creation of a new A I want to execute the following code in an observer of A:

public function creating(\Process $model)
{
    $model->getConnection()->beginTransaction();
}

public function created(\A $model)
{
    $b = new \B();
    $b->bRelationships()->associate($model);
    if (! $b->save()) {
        return false;
    }

    $model->getConnection()->commit();
}

The code has to be executed after a new A has already been created in the database, because otherwise the foreign key constraint on the B model would fail.

Currently the only option to actually stop the creation is to manually start a transaction in the pre-event and then throw an Exception in the post event if something failed. This will result in the database to remain in a legal state at all times but the application will fail rather ungracefully because of the exception. To circumvent this you would have to write the following code for every save of an A:

try {
    if (! $a->save()) {
        // Error handling
    }           
} catch (\Exception $e) {
    // Same error handling
}

In my opinion this is unnecessarily verbose and furthermore rather unintuitive. My ideal solution would be that every model save automatically starts a transaction before saving and if an error happens in one of the listeners it would automatically roll back all changes.

All 2 comments

Just closed without any comment at all?

Honestly, this is too long to read. If you think something can be improved, please send a pull request. That would be much more helpful.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

shopblocks picture shopblocks  路  3Comments

YannPl picture YannPl  路  3Comments

ghost picture ghost  路  3Comments

JamborJan picture JamborJan  路  3Comments

progmars picture progmars  路  3Comments