In Laravel, database transactions are used to manage the integrity and consistency of the database when performing multiple database operations together. A transaction is a set of database operations that are executed as a single unit of work. If any part of the transaction fails, all the changes made within that transaction are rolled back, ensuring that the database remains in a consistent state.
DB::beginTransaction();
try {
// Perform database operations here
User::where('age', '>', 25)->delete();
if(User::where('status',User::DRAFT)->first()){
// Performing Database Operations
}
// Commit the transaction
DB::commit();
} catch (\Exception $e) {
// Something went wrong, rollback the transaction
report($e);
DB::rollback();
}
Top comments (1)
Good, Johny.
However, I usually prefer the
DB::transaction()
method, that is: