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,
A
fails to save, the code ends gracefullyB
fails to save, it removes its corresponding A
recordC
fails to save, it removes its corresponding B
and A
recordHow do I do this?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With