Skip to content

andreaskviby/Optimistic-Locking

Repository files navigation

Optimistic Locking

Optimistic Locking

Utilities for implementing optimistic locking in Laravel Eloquent models.

Features

  • 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 via diff().
  • Artisan command schema:lock --apply adds the locking column to tables under app/Models.
  • Fully configurable column name, start value and diff length.

Requirements

  • PHP 8.1+
  • Laravel 10, 11 or 12

Installation

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();

Usage

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());
}

Configuration

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.

Testing

composer test

Changelog

See CHANGELOG for a record of changes.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Security

If you discover a security vulnerability, please contact the maintainer at developer@example.com.

License

The MIT License. See LICENSE.md for details.

About

Optimistic Locking

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages