Problems with rollback in Laravel 5.5

1

I'm doing the import / migration of an old database from a my site to a new format. I am using Transactions on this import, as per the code below.

The problem is that when I make an error the rollback is not being triggered. For example I have 5 records that will be included in a batch within begintransaction and I have an error in record 3. The exception is generated treated but when I look in the database the 3 records were even included with the error.

What I'm doing wrong. Thanks

$erros = new Erros();
\DB::beginTransaction();
try {         
        $pesq = $original->whereIn('cod', $request->get('codigo'))->get();            
        foreach ($pesq as $valores) {                
            $temp = [
                'id' => $valores->codigo,
                'plano_id' => 0,                    
                'cliques' => $valores->qtd_cliques,                    
                'caracteristicas' => $valores->caracteristicas,                    
                'destaque' => ($valores->destaque == 0) ? 1 : 0,
                'imagem' => $valores->imagemDestaque,                    
                'created_at' => $valores->created_at,
                'updated_at' => $valores->updated_at,
                'deleted_at' => $valores->deleted_at,
            ];

            \DB::table('casas')->insert($temp);                

            if(strlen($valores->filme)>2){
                throw new \Exception('Este imóvel contém 1 video que deve ser incluído manualmente.');
            }
        }
        \DB::commit();
} catch (\Exception $e) {
        \DB::rollback();
        $erros->setId($valores->codigo);
        $erros->setCodigo($e->getCode());
        $erros->setMensagem($e->getMessage());
}
    
asked by anonymous 11.01.2018 / 01:42

2 answers

0

After much trying together with Dinaerte Neto of the Laravel Brazil group of Facebook we verified that the problem was that the table was of type MyISAM and it seems that it does not support transactions. I switched to INODB and everything was fine.

    
11.01.2018 / 17:18
0

To catch the exceptions generated by the bank use \PDOException , \Exception does not capture this type of error. Possibly because the error is not being captured the transaction occurs normalmente .

Within your if , an exception is also being generated, thus interrupting the execution flow of the code, put a DB::rollback() in that snippet as well.

    
11.01.2018 / 01:55