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'); }); // ...}