samedi 26 décembre 2015

How to rollback new records if a later record fails to add in Laravel 5?

In my controller I have code similar to the following:

$a = new A();
$a->content = "blah";
$a->save();

$b = new B();
$b->content = "blah2";
$b->a_id = $a->id;
$b->save();

$c = new C();
$c->content = "blah3";
$c->b_id = $b->id;

where A, B and C are all models.

As you can see, each model assignment relies on the previous record being assigned correctly (i.e. C relies on B, and B relies on C)

I want to make the code so that if one of the new records fails, it deletes all previous records (i.e. all or nothing).

For example,

  • If A fails to save, the code ends gracefully
  • If B fails to save, it removes its corresponding A record
  • If C fails to save, it removes its corresponding B and A record

How do I do this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire