0

I am trying to do a transaction in the db with Eloquent ORM following the instructions here: https://stackoverflow.com/a/15105781/5649969

I notice that the code throws a Throwable, so I put it in a try...catch block to go for an early return if there is an exception.

try {
    DB::transaction(function () use ($user, $attributes) {
        $validUserAttributes = $user->getFillable();
        $updatable = [];
        foreach ($attributes as $key => $value) {
            if (in_array($key, $validUserAttributes)) {
                $updatable[$key] = $value;
            }
        }
        $user->update($updatable);

        $validRoleAttributes = $user->role->getFillable();
        $updatable = [];
        foreach ($attributes as $key => $value) {
            if (in_array($key, $validRoleAttributes)) {
                $updatable[$key] = $value;
            }
        }
        $user->role()->update($updatable);
    });
} catch (Throwable $_) {
    dd(1000);
    return new UpdateUserResult(false, UpdateUserResult::UPDATE_FAILED);
}

dd(2000);
return new UpdateUserResult(true, UpdateUserResult::UPDATE_SUCCESS);

This is where my problem is, it seems that the early return does not work for whatever reason, when I remove the dd(2000), dd(1000) will run, why does the code seem like it is running from the bottom to the top?

Tom
  • 25
  • 7
  • What does dd(?) do? – Petr 'PePa' Pavel Feb 11 '22 at 10:47
  • @Petr'PePa'Pavel `dd` is short for dump and die, it is a helper in laravel, more info about `dd` at [doc](https://laravel.com/docs/8.x/helpers#method-dd) – Tom Feb 11 '22 at 18:19
  • Perhaps your code is executed twice - first time it goes through and dies with 2000. Therefore it's prevented to be executed for the second time and die with 1000. XDebug is a much better tool for debugging. It's worth the time invested into setting it up. – Petr 'PePa' Pavel Feb 11 '22 at 18:22
  • I've given up on using the above to do it due to lack of time- I used a workaround where I save the old model data in a variable first, then revert the first model's (in this case, `User`) if the second model (`Role`) data fails to get updated. – Tom Feb 16 '22 at 04:52

0 Answers0