News

Pessimistic Locking in Laravel Eloquent with refreshForUpdate()

Published
Pessimistic Locking in Laravel Eloquent with refreshForUpdate() image

Eloquent has had refresh() for reloading a model from the database, and lockForUpdate() for taking a row lock as part of a query. What it has not had is a way to do both to a model instance. Laravel 13.27 adds refreshForUpdate(), contributed by @stevebauman in #61247.

What It Does

The method reloads the model by its primary key with FOR UPDATE applied, and updates the instance in place:

public function refreshForUpdate()
{
if (! $this->exists) {
return $this;
}
 
return $this->refreshUsingQuery(
$this->newQueryWithoutScopes()->lockForUpdate()
);
}

refreshUsingQuery() is the same helper behind refresh(). It scopes the query to the model's key, sends it through useWritePdo() so a read replica cannot serve a lock you are about to depend on, calls firstOrFail(), replaces the raw attributes, reloads any relations that were already loaded, and syncs the original attribute state. The only thing refreshForUpdate() adds is the lock.

Before the refreshUsingQuery() method, safely decrementing a product's stock would look like the following:

public function purchase(Product $product): Response
{
DB::transaction(function () use ($product) {
$product = Product::query()
->lockForUpdate()
->findOrFail($product->getKey());
 
if ($product->stock === 0) {
throw new RuntimeException('The product is out of stock.');
}
 
$product->decrement('stock');
});
 
// ...
}

Now, you can refresh and lock a model directly using refreshForUpdate():

public function purchase(Product $product): Response
{
DB::transaction(function () use ($product) {
$product->refreshForUpdate();
 
if ($product->stock === 0) {
throw new RuntimeException('The product is out of stock.');
}
 
$product->decrement('stock');
});
 
// ...
}

Further Reading

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
Taylor disabled GitHub Issues on most Laravel open-source packages. image

Taylor disabled GitHub Issues on most Laravel open-source packages.

Read article
Exclude Vendor and Default Commands in `php artisan dev` image

Exclude Vendor and Default Commands in `php artisan dev`

Read article
The Laracon Archive image

The Laracon Archive

Read article
Group Adjacent Collection Items in Laravel with chunkBy() image

Group Adjacent Collection Items in Laravel with chunkBy()

Read article
Laravel queue:work Now Prints Why the Worker Stopped image

Laravel queue:work Now Prints Why the Worker Stopped

Read article
Sidecar Brings Statamic's Control Panel to Your Existing Markdown Sites image

Sidecar Brings Statamic's Control Panel to Your Existing Markdown Sites

Read article