Reputation:
I have some forms that i want to commit to the database. However my code so far is in eloquent orm
$user->password = bcrypt($newPassword);
$user->save()
I want to transform all code that updates,deletes or creates into the database to use database transactions. Is doing this
\DB::beginTransaction();
$user->password = bcrypt($newPassword);
$user->save()
\DB::commit();
enough for me to have a transaction?.
Upvotes: 0
Views: 7554
Reputation: 10166
As you can found in the official documentation:
DB::transaction(function () {
//Operations on db
});
It will automatically rollback if an exception is thrown inside the closure.
Upvotes: 0
Reputation: 3679
yes just add try catch
or you can use automatic way:
DB::transaction(function ($user) {
$user->password = bcrypt($newPassword);
$user->save()
});
EDIT : best practice to write manually transaction:
try {
\DB::beginTransaction();
$user->password = bcrypt($newPassword);
$user->save()
\DB::commit();
}catch(\Exception $e){
\DB::rollback();
}
Upvotes: 1