How to rollback new records if a later record fails to add in Laravel 5?
Ad
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 correspondingA
record - If
C
fails to save, it removes its correspondingB
andA
record
How do I do this?
Ad
Answer
Ad
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
Ad
source: stackoverflow.com
Related Questions
Ad
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad