Skip to content

Commit 33fee97

Browse files
DarkGhostHuntertaylorotwell
andauthoredJan 15, 2025
Add pessimistic locking extended example (#10113)
* Add pessimistic locking extended example * Update queries.md --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent 29a04f0 commit 33fee97

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
 

‎queries.md

+28
Original file line numberDiff line numberDiff line change
@@ -1191,6 +1191,34 @@ Alternatively, you may use the `lockForUpdate` method. A "for update" lock preve
11911191
->lockForUpdate()
11921192
->get();
11931193

1194+
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:
1195+
1196+
DB::transaction(function () {
1197+
$sender = DB::table('users')
1198+
->lockForUpdate()
1199+
->find(1);
1200+
1201+
$receiver = DB::table('users')
1202+
->lockForUpdate();
1203+
->find(2);
1204+
1205+
if ($user->balance < 100) {
1206+
throw new RuntimeException('Balance too low.');
1207+
}
1208+
1209+
DB::table('users')
1210+
->where('id', $sender->id)
1211+
->update([
1212+
'balance' => $sender->balance - 100
1213+
]);
1214+
1215+
DB::table('users')
1216+
->where('id', $receiver->id)
1217+
->update([
1218+
'balance' => $receiver->balance + 100
1219+
]);
1220+
});
1221+
11941222
<a name="debugging"></a>
11951223
## Debugging
11961224

0 commit comments

Comments
 (0)
Please sign in to comment.