Create method in laravel with rollback

1

I was studying laravel 5.4 and I had a question. As a good programmer I researched google in many ways and found nothing like it.

Imagine the following case:

$prod = $this->product->create([
    name -> 'produto 1',
    valor -> '100',
    active -> '0'
]);

if($prod){
    $id = $prod->id;

    $tProd = $this->relTypeProduct->create([
        idProduct -> $id,
        idTypeProduct -> 1
    ]);

    if($tProd){
        $message = 'Produto cadastrado com sucesso!';
        DB::commit();
        return true;
    }else{
        $message = 'Erro ao cadastrar o tipo de produto!';
        DB::rollback();
        return false;
    }
}else{
    $message = 'Erro ao cadastrar o tipo de produto!';
    return false;
}

I want you to make a mistake in the second create , and give it a rollback() to delete the first create . But is not this happening, it is the first create the $prod receives true and gives an error in the second create , it does not give the rollback .

DB:commit() and DB:rollback() does not work in this case. Would anyone have a solution for this?

    
asked by anonymous 14.06.2018 / 17:45

1 answer

1

I solved by entering DB::beginTransaction(); at the beginning of my code.

DB::beginTransaction();

$prod = $this->product->create([
    name -> 'produto 1',
    valor -> '100',
    active -> '0'
]);
if($prod){
    $id = $prod->id;

    $tProd = $this->relTypeProduct->create([
        idProduct -> $id,
        idTypeProduct -> 1
    ]);

    if($tProd){
        $message = 'Produto cadastrado com sucesso!';
        DB::commit();
        return true;
    }else{
        $message = 'Erro ao cadastrar o tipo de produto!';
        DB::rollback();
        return false;
    }
}else{
    $message = 'Erro ao cadastrar o tipo de produto!';
    return false;
}
    
14.06.2018 / 20:45