Transaction rolls back in Ravel 5.8 for some reason

Asked 2 years ago, Updated 2 years ago, 106 views

Thank you for your continuous support.
Developed in Ravel 5.8/php 7.3.
Since there was multiple tables of insert processing, we are processing transactions using \DB::transaction.

In the local environment, I was able to register multiple tables without any problems, but somehow when I upload them to the production environment, they are not registered.

function__invoke(){
    $uesr = $this->store();
    var_dump($user);//< - Registered content has been retrieved and newly registered ID has been issued
}
function store() {
    return\DB::transaction(function()use(){
        $data=['email'=>'[email protected]', name'=>'test'];
        $user = new User;
        $user->fill($data)->save();

        $post=Post::create(['user_id'=>$user->id]);
        return$user;
    });
}

As mentioned above, the transaction process has been completed, and var_dump has been able to obtain the newly issued ID.
However, it is not registered in the database, and it seems that it has been rolled back.

  • Register successfully once transaction processing is stopped
  • When an error (Exception) occurs in a transaction, var_dump is not displayed

I have checked and would appreciate it if you could let me know if there is anything else I need to check or correct.

Thank you for your cooperation.

php laravel-5

2022-09-30 21:41

1 Answers

Isn't $user_id $user->id?

It's a snake-footed transaction, but if you surround it with try/catch, you can catch an exception when you roll back, so it's easy to grasp the cause.
"Also, if the user and post are in a relationship, it is better to use ""insert related models"" to be aware of the id."

try{
    $user=\DB::transaction(function(){
        // preservation
        $user=User::create(['email'=>'[email protected]', 'name'=>'test']);
        $post=$user->posts()->create(['comment'=>'comment']);
        return$user;
    )};
} catch(\Exception$e){
    report($e);
    // What to do during Rollback
}

*There may be a typo for the code.


2022-09-30 21:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.