Laravel Database Rollback When Exceptions Happen

Sometimes we need to save data in a multiple table at a time. In this case we can use laravel database transaction to do it. We use database transaction to handle such kind of situations like that.

DB::beginTransaction();
try {

}
catch(\Exception $e)
{
	DB::rollback();
    throw $e;
}
DB::commit();

 

But you know that we can create our own middleware to do the same task. Look we can create a middleware where we will write same condition for our database transaction.  So how can we take the concept of database transactions and wrap requests up inside them?

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;
    }
}

 

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

 

Hope it can help you.

 

author-image
Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js