Skip to content
Advertisement

Laravel: Using try…catch with DB::transaction()

We all use DB::transaction() for multiple insert queries. In doing so, should a try...catch be placed inside it or wrapping it? Is it even necessary to include a try...catch when a transaction will automatically fail if something goes wrong?

Sample try...catch wrapping a transaction:

JavaScript

The opposite, a DB::transaction() wrapping a try…catch:

JavaScript

Or simply a transaction w/o a try…catch

JavaScript

Advertisement

Answer

In the case you need to manually ‘exit’ a transaction through code (be it through an exception or simply checking an error state) you shouldn’t use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():

JavaScript

See the transaction docs.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement