Tomas C. Lopes
Tomas C. Lopes

Reputation: 109

Laravel - On Catch Delete Created Object

So, I am submitting a form with 3 components, user -> company -> branch.

Right now, if I catch an error in any child object, I am unable to delete the parent records and when the user tries to resubmit the form he can't use the same details because they're already registed.

My question is:

Can I delete the objects created within try{} in catch{} ?

If not, what practice do you recommend to handle this type of situations?

Thanks in advance!

Upvotes: 1

Views: 410

Answers (1)

Aashish gaba
Aashish gaba

Reputation: 1776

You can use transactions for that scenario.

Let's say you have multiple create/update/delete and if one of them fails you want it to undo the others, then transaction comes to the rescue.

DB::transaction(function () {
    User::create([...]);
    Company::create([...]);
    Branch::create([...]);
});

So here if any one of the above statement fails, other statements are rolled back.

You can read in detail in the documentation. https://laravel.com/docs/7.x/database#database-transactions

Upvotes: 2

Related Questions