harvey_slash harvey_slash - 4 months ago 9x
MySQL Question

Laravel and Transaction , okay to catch errors?

I have a transaction like so :

return DB::transaction(function() use($intersectedArray,$user,$currentTime) {
try {
foreach ($intersectedArray as $subItemId) {
$user->todoSubItems()->updateExistingPivot($subItemId, ["done" => 1]);
catch (Exception $e){
return response()->json(500);

return response()->json($intersectedArray, 200);

first of all , is it okay to run a loop inside like that ?(If a single query fails to update , I want the entire transaction to be rolled back.

2ndly , will the transaction still roll back even if I catch the error inside like that ?or will that prevent the transaction from working ?


You'll want to do DB::rollBack(); before returning the 500 error.

Transactions get rolled back only if an uncaught exception is encountered. As you're catching the exception, it won't rollback unless you do so explicitly.