Home » Php » php – How to rollback new records if a later record fails to add in Laravel 5?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

It’s really simple, use database transactions:

DB::transaction(function () {

    $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;

});

Everything here will be done automatically – if any of above fail, result will be same as the code inside transactions has never been run.

Reference: Laravel database transactions

EDIT

If you need to pass any variables, you need use use construction like so:

DB::transaction(function () use ($variable1, $variable2) {
  // ...
});

Reference: Anonymous functions