Home >Backend Development >PHP Tutorial >Managing Data Races with Pessimistic Locking in Laravel

Managing Data Races with Pessimistic Locking in Laravel

百草
百草Original
2025-03-05 15:32:18921browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn