1

What if user call two requests, which checks user balance then perform operation on balance. Can it cause any problems? For example those two codes:

$user = User::find(1);
if($user['balance']>250) {
    // Here for example long loop
    $user->update([
        'balance' => DB:raw('balance - 100')
    ]);
}

And second script doing similiar thing. Can be situation like: in first request if statement is passed , then long loop is executed, and in same time second request runing which has if checking balance and this if executes before $user->update() is excuted in first request, so can user pass if statement when he does not have balance?

1
  • You can enclose your code in a database transaction, the functions to use depends on your framework. Commented Mar 1, 2019 at 23:19

1 Answer 1

1

Yes, it can be such situation. To avoid this use LOCK/UNLOCK TABLE

$user = User::find(1);
if($user['balance']>250) {
    User::lockTable(); // method name/use depends on your framework
    // Here for example long loop
    $user->update([
        'balance' => DB:raw('balance - 100')
    ]);
    User::unlockTable();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.