How to prevent errors when saving multiple models in Laravel 5

740 views Asked by At

I am trying to modify several models (Laravel 5) in one of my controllers, so I receive all the info I need from a very large form, and then find the models in my database, modify them and finally save them in order to keep the changes.

But, lets say I am saving 5 different models, one after the other, and when the system is trying to save the 3rd model (for example), something goes wrong and the process ends. How can I revert the previous changes, so I don't save partial changes?

Any idea would be appreciated. Thanks.

1

There are 1 answers

0
ceejayoz On BEST ANSWER

You'd use a transaction for this.

$model1 = new Foo;
$model2 = new Bar;


DB::transaction(function() use($model1, $model2) {
  $model1->save();
  $model2->save();
}

If an exception occurs within the DB::transaction block, all changes within it will be rolled back.