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

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
Mask Query Bindings in Laravel Exception Messages image

Mask Query Bindings in Laravel Exception Messages

Read article
whereBinary(): Case-Sensitive MySQL Queries in Laravel image

whereBinary(): Case-Sensitive MySQL Queries in Laravel

Read article
Compile PHP to Native Binaries with TypePHP image

Compile PHP to Native Binaries with TypePHP

Read article
State of Laravel 2026 Survey Is Now Open image

State of Laravel 2026 Survey Is Now Open

Read article
Testing Best Practices Skill in Laravel Boost v2.6.0 image

Testing Best Practices Skill in Laravel Boost v2.6.0

Read article
Query Binding Masking and whereBinary() in Laravel 13.27 image

Query Binding Masking and whereBinary() in Laravel 13.27

Read article