Rollback Your Database Changes 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 : How to Get Todays Record From Database In Laravel

 

Hope it can help you.