Try catch & DB Rollback


Recently I came across a peculiar issue, which I have never met before.

My coding structure was as follows:


Why this Happened?

The first reason to not get the try catch was that I had not used Exception. So in the beginning of the file I included ‘use Exception’

When the DB::beginTransaction was used before the foreach loop, it encounters the first exception and does the roll back, but does not apply a new DB::beginTransaction for the next item. Therefore rest of the items are committed to the db, as they happen.

Solution for this ->

The solution was to include the DB::beginTransaction within the loop. So the corrected coding looked like follows: