Utilities for implementing optimistic locking in Laravel Eloquent models.
OptimisticLocking
trait increments a version column every time a model is updated.StaleModelException
is thrown when an outdated model instance is saved and exposes the changed values viadiff()
.- Artisan command
schema:lock --apply
adds the locking column to tables underapp/Models
. - Fully configurable column name, start value and diff length.
- PHP 8.1+
- Laravel 10, 11 or 12
Install the package via composer:
composer require stafe/optimistic-locking
Publish the configuration file to customise the column name or initial value:
php artisan vendor:publish --tag="optimistic-locking-config"
Add a locking column to your tables. Either run the command that scans your models:
php artisan schema:lock --apply
or add the column manually in your migrations:
$table->unsignedInteger('lock_version')->nullable();
Apply the trait to any model that needs optimistic locking:
use Stafe\OptimisticLocking\Traits\OptimisticLocking;
class Post extends Model
{
use OptimisticLocking;
}
When a stale model instance is saved the package throws a StaleModelException
:
try {
$post->save();
} catch (Stafe\OptimisticLocking\StaleModelException $e) {
logger()->warning('Stale update', $e->diff());
}
The published configuration file looks like this:
return [
'column' => 'lock_version',
'start_value' => 1,
'diff_max_len' => 250,
];
Adjust these options to match your application.
composer test
See CHANGELOG for a record of changes.
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
If you discover a security vulnerability, please contact the maintainer at developer@example.com.
The MIT License. See LICENSE.md for details.