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());
}