Database transactions are used to run a set of queries or database operations that depend on each other, and if one fails you can easily rollback.

Take an example you want to create a user and then assign a role. You want to make sure that if a user is created and the role must also be assigned. If role assignment fails, then the user should also not be in the database. For these applications, use transactions.

1. Begin the transaction

Use DB facade's beginTransaction method to start the transaction, all the queries that run after the beginTransaction call, will not be persisted to database, until you commit them.

use Illuminate\Support\Facades\DB;

DB::beginTransaction();

2. Write your queries

After the transaction is begun, you can then write your queries as you normally would.

DB::update('update users set votes = 1');

DB::delete('delete from posts');

3. Persist or rollback the queries

You can then rollback or commit your queries depending on the success of your process.

DB::commit();

Or if the transaction did not succeed,

DB::rollback();

And that's it your done!


Still stuck around? Great, here are some bonuses for you..

Use try catch to rollback automatically

You can wrap your queries inside the try catch block in order to catch errors and rollback when they are thrown

try{
	DB::beginTransaction();
    
    DB::update('update users set votes = 1');

	DB::delete('delete from posts');
    
    DB::commit();
catch(\Exception $e){
	DB::rollback();
    throw $e;
}
	

You can use the closure method as shorthand

You may use the transaction method provided by the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction closure, the transaction will automatically be rolled back. If the closure executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method:

use Illuminate\Support\Facades\DB;

DB::transaction(function () {
    DB::update('update users set votes = 1');

    DB::delete('delete from posts');
});
from laravel doc

Handle deadlocks

The transaction method accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs. Once these attempts have been exhausted, an exception will be thrown:

use Illuminate\Support\Facades\DB;

DB::transaction(function () {
    DB::update('update users set votes = 1');

    DB::delete('delete from posts');
}, 5);
from laravel doc