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

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Inertia DevTools Now Available for Firefox image

Inertia DevTools Now Available for Firefox

Read article
Laravel Scalpel Scans for Filesystem Intrusion Evidence image

Laravel Scalpel Scans for Filesystem Intrusion Evidence

Read article
Mercure Broadcasting in Laravel 13.32 image

Mercure Broadcasting in Laravel 13.32

Read article
Super Stack: Laravel Starter Kit With Filament and NativePHP image

Super Stack: Laravel Starter Kit With Filament and NativePHP

Read article
Laravel MCP 1.0 Is Released image

Laravel MCP 1.0 Is Released

Read article
Laravel Vet: Review Composer Code Before It Installs image

Laravel Vet: Review Composer Code Before It Installs

Read article