Skip to content
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