Create method in the Windows with rollback

Asked

Viewed 291 times

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.

  • 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.

  • Have you read my comment? To do this you need to use a transaction.

  • Got it, thanks a lot for your help.

1 answer

1

I decided to insert 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.