gabrielmzl's avatar

Laravel transactions not working rollback

I would like to know why the rollback doesn't work? From what I understood, the user was only supposed to be created if there was no error. But my current code creates the user even if it gives the simulated error, could anyone help me?

public function Teste() { DB::beginTransaction();

    try {
        $Cliente = Cliente::create([
            'Nome' => 'Teste',
            'Email' => '[email protected]',
            'CPF' => '12345678901',
            'Telefone' => '11999999999',
            'Data_de_Nascimento' => '1990-01-01',
            'Verificado' => true
        ]);

        throw new \Exception('Erro simulado');

        DB::commit();

        return 'Transação bem-sucedida';
    } catch (\Exception $e) {
        DB::rollBack();
        return 'Erro na transação: ' . $e->getMessage();
    }
}
0 likes
9 replies
Snapey's avatar

Not answering your question, but you never need to use a transaction when only updating one table.

gabrielmzl's avatar

@Snapey This I know, I did it just to test. Because I can't make it work at all.

gabrielmzl's avatar

@Snapey Yes, I receive it. However, the transaction is not rolled back from the database.

Tray2's avatar

@Snapey Not entirely true, there are in some cases a need for it, if you want to make sure that the code isn't updated while you are updating it. For example when you run jobs in parallel.

Snapey's avatar

@Tray2 How does a transaction help? If two jobs write to the same record and one has out of data information then both will work and the last write will take precedence.

Tray2's avatar

@Snapey You can use SELECT * FROM table1 WHERE some_column = 'Some Value' FOR UPDATE SKIP LOCKED, that means that if the record is already locked by another session, it will not even be considered as a candidate, if you don't the database will wait until the record is released before updating and continuing to run.

MohamedTammam's avatar

If you're using MySQL make sure that your engine is InnoDB and not MyISAM

Please or to participate in this conversation.