Laravel Pessimistic Locking: Easy Guide with Examples

ArjunAmrutiya
3 min readOct 4, 2024

Introduction:
Pessimistic Locking is a strategy to prevent data conflicts during concurrent database operations.
It locks the selected rows to ensure no other transaction can modify or even read them until the lock is released. This guarantees data consistency and prevents race conditions.

lockForUpdate():
Use lockForUpdate() when you want to ensure no other transaction can read or modify the locked rows until the current transaction is completed.

DB::table('products')
->where('id', 1)
->lockForUpdate()
->first();

In this example, we lock the product row with id = 1. If another transaction tries to read or modify this row, it will have to wait until the lock is released, ensuring that no changes occur until the current transaction is complete.

sharedLock() :
Use sharedLock() when you want to allow read operations but prevent any modifications to the locked rows.

DB::table('products')
->where('category', 'electronics')
->sharedLock()
->get();

This example locks all rows in the electronics category, allowing other transactions to read the rows but not modify them. If a transaction tries to update or delete these rows, it will be…

--

--

ArjunAmrutiya
ArjunAmrutiya

Written by ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!

No responses yet