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 →
Running Laravel's Scheduler on Multiple Servers image

Running Laravel's Scheduler on Multiple Servers

Read article
Laravel Fake Assertions Now Accept Property Arrays image

Laravel Fake Assertions Now Accept Property Arrays

Read article
Route::query() and Model defaults() in Laravel 13.35 image

Route::query() and Model defaults() in Laravel 13.35

Read article
Laravel AI SDK 1.1 Adds Agent Skills and Cohere Chat image

Laravel AI SDK 1.1 Adds Agent Skills and Cohere Chat

Read article
VMPal: Give Your AI Agent a Whole Computer image

VMPal: Give Your AI Agent a Whole Computer

Read article
Synapse: A Dev Dashboard for Laravel AI SDK Agents image

Synapse: A Dev Dashboard for Laravel AI SDK Agents

Read article