01

How to Use Transactions in Laravel Query builder?

Transaction is very familiar concept in SQL. We group more than one queries in a transaction. If any query will fail then whole transaction will fail and all queries will rollback even if they are executed. It is all or none strategy. We can use transactions very conveniently in Laravel query builder. It throws exception if any query fails and it will rollback all queries.

DB::transaction( function () use ( $id, $points ) {
	DB::table( "leads" )->where( 'id', $id )->update( [ 'points' => $points ] );
        DB::table('meta')->where('lead_id', $id)->delete();
} );

Note that you can also manually begin and end transactions—and this applies both for query builder queries and for Eloquent queries. Start with DB::beginTransaction(), end with DB::commit(), and abort with DB::rollBack():

I hope you will understand everything about transactions. If you have any problem please leave a comment. We appreciate that.