1
I was studying Laravel 5.4 and I came up with a question. As a good programmer I googled several ways and found nothing like.
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, he gives a rollback() to erase the first create.
But it’s not happening, it makes the first create the variable $prod receives true and if there’s an error in the second create, he doesn’t give the rollback.
The DB:commit() and the DB:rollback() does not work in this case. Someone would have a solution for this?
You need to do the operation within a transaction to be able to use commits and rollbacks.
– Jéf Bueno
What is a Mysql Transaction for?
– Jéf Bueno
The first Create it registers in the bank, the problem is that, I would like you to give a rollback if the second create gives some error.
– Arthur Calazans
Have you read my comment? To do this you need to use a transaction.
– Jéf Bueno
Got it, thanks a lot for your help.
– Arthur Calazans