0
  • Laravel: 10.3.3
  • PostgreSQL 10.23

SIMPLE CODE:

DB::beginTransaction();
try{
    $parent = new Parent($postAttributes);
    if($parent ->save()){
        $child = new Child($postAttributes);
        $child->save(); <- Here fire exception purposely

       //anything else
        DB::table('users')->insert([
            'email' => 'kayla@example.com',
            'status' => 1
        ]);
        
    }
}catch(Exception $ex){
    DB::rollback();
}

DB::commit();

In this case, parent model was saved! Child model fire exception but laravel, or postgres, dont rollback changes!

Someone can helps me?

Owwww... Wait ! Yes I've already tried DB::transaction(function () {}) too !

  • I expect transactions to be "rollback" when there is any error

1 Answers1

0

reordering beginTransaction() and commit() works like below.

try
{
    DB::beginTransaction();
    $parent = new Parent($postAttributes);
    if($parent ->save())
    {
        $child = new Child($postAttributes);
        $child->save(); <- Here fire exception purposely

       //anything else
        DB::table('users')->insert([
            'email' => 'kayla@example.com',
            'status' => 1
        ]);
    }
    DB::commit();
}
catch(Exception $ex)
{
    DB::rollback();
}

more explained on comment of this post by alexrussell Laravel: Using try...catch with DB::transaction()

Zafeer Ahmad
  • 240
  • 5
  • 17