Laravel lockforupdate (Pessimistic Locking)
This work, finally, but still don't understand what sharedLock(LOCK IN SHARE MODE) and lockForUpdate(FOR UPDATE) different
public function index() {
return dd(\DB::transaction(function() {
if (\Auth::guard('user')->check()) {
$model = \App\Models\User::lockForUpdate()->find(1);
sleep(30);
$model->point = 100000;
$model->save();
} else {
$model = \App\Models\User::lockForUpdate()->find(1);
$model->point = $model->point + 1;
$model->save();
}
return $model;
}));
}
So this is old question but I believe my answer can clarify how ->lockForUpdate()
works
From Laravel documentation:
A shared lock prevents the selected rows from being modified until your transaction is committed.
So as it is written - lock will be active from when you call it until your transaction is done.
Remember:
->find(1)
works like ->first()
, ->get()
, ->insert()
, ->save()
etc. - it executes the query
->lockForUpdate()
works like ->where()
, ->select()
, join()
etc. - it adds to the query, but doesn't execute it
$model = \App\Models\User::find(1)->lockForUpdate();
- you try to add lock after query has already executed
$model = \App\Models\User::lockForUpdate()->find(1);
- you add lock before query is executed therefore lock is active until transaction is finished
Difference is that in 1st scenario ->lockForUpdate()
wasn't executed when you taught that it was