Rollback Database When Exceptions Happen In Laravel

We all are facing such situation that we need to save multiple table at a same time. What do you do that situation? Sometimes there is dependency that one table is dependent another table. We can use database transaction in this situation to handle it.

We can 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:

DB::beginTransaction();
try {
  //code goes here
}
catch(\Exception $e)
{
	DB::rollback();
    throw $e;
}
DB::commit();

 

Read also : When and How to Use Database Transactions in Laravel

 

But do you know that we may create our middleware to have the same performance. Look we may create a middleware where we will write same condition for our database transaction.  

With middleware! We can write some middleware that will wrap the request inside a database transaction and commit the transaction if everything was successful.

Here's what this looks like:

use Illuminate\Support\Facades\DB;

class WrapRequestInDatabaseTransaction
{
    public function handle($request, Closure $next)
    {
        DB::beginTransaction();

        $response = $next($request);

        if ($response->exception) {
            DB::rollBack();
            return $response;
        }

        DB::commit();

        return $response;
    }
}

 

Hope it can help you.

 

#laravel #laravel-8x #database