Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pessimistic locking extended example #10113

Merged
merged 2 commits into from
Jan 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -1191,6 +1191,34 @@ Alternatively, you may use the `lockForUpdate` method. A "for update" lock preve
->lockForUpdate()
->get();

It is recommended, but not obligatory, to wrap pessimistic locks inside a [transaction](/docs/{{version}}/database#database-transactions), especially when you require the data retrieved to not be altered on the database until the entire transaction is finished. If the transaction fails, the locks will be freed and any changes will be rolled back:

DB::transaction(function () {
$sender = DB::table('users')
->lockForUpdate()
->find(1);

$receiver = DB::table('users')
->lockForUpdate();
->find(2);

if ($user->balance < 100) {
throw new RuntimeException('Balance too low.');
}

DB::table('users')
->where('id', $sender->id)
->update([
'balance' => $sender->balance - 100
]);

DB::table('users')
->where('id', $receiver->id)
->update([
'balance' => $receiver->balance + 100
]);
});

<a name="debugging"></a>
## Debugging

Expand Down