Home >Backend Development >PHP Tutorial >Managing Data Races with Pessimistic Locking in Laravel
Laravel framework provides a powerful pessimistic locking mechanism to effectively prevent data competition in concurrent database operations. The sharedLock()
and lockForUpdate()
methods allow you to maintain data consistency in high concurrency scenarios.
sharedLock()
method allows reading, but prevents modification:
DB::table('users') ->where('votes', '>', 100) ->sharedLock() ->get();
For stricter control, the lockForUpdate()
method prevents modification and sharing of locks at the same time:
DB::table('orders') ->where('status', 'pending') ->lockForUpdate() ->get();
This method is particularly important in financial transactions or inventory management systems:
class PaymentController extends Controller { public function processPayment($orderId, $amount) { return DB::transaction(function () use ($orderId, $amount) { $account = DB::table('accounts') ->where('order_id', $orderId) ->lockForUpdate() ->first(); if ($account->balance >= $amount) { DB::table('accounts') ->where('order_id', $orderId) ->update(['balance' => $account->balance - $amount]); return ['success' => true, 'message' => 'Payment processed successfully']; } return ['success' => false, 'message' => 'Insufficient funds']; }); } }
In applications that need to ensure data accuracy, multiple processes may try to modify the same data at the same time, and these locking mechanisms are crucial.
The above is the detailed content of Managing Data Races with Pessimistic Locking in Laravel. For more information, please follow other related articles on the PHP Chinese website!