Reputation: 8509
Hello I have two tables in my database:
When i add a new user, data is also saved into the user_profile table. I am considering a situation where for some reason the data is able to save into the user table but not the user_profile table.
I would want the data in the users table to be removed to avoid any broken records, since my user and user_profile table depend on each other.
What is the best way to achieve this?
Upvotes: 0
Views: 467
Reputation: 4755
You can use database transactions. The simplest way to use them is
DB::transaction(function()
{
// Do something that alters 'users' table
// Do something that alters 'user_profiles' table
});
If any of the above operation fails (throws an exception) all the operations will be cancelled and your database will be untouched. If you need more control over the transaction, you can do this
try {
DB::beginTransaction();
// Do something that alters 'users' table
// Do something that alters 'user_profiles' table
if($somethingWentWrong)
throw new Exception('something went wrong');
// Everything OK
DB::commit();
} catch (\PDOException $e) {
// something went wrong with the database
DB::rollBack();
} catch (\Exception $e) {
// something went wrong
DB::rollBack();
}
Upvotes: 2