An open API service indexing awesome lists of open source software.

https://github.com/reshadman/laravel-optimistic-locking

Adds optimistic locking feature to eloquent models.
https://github.com/reshadman/laravel-optimistic-locking

database eloquent laravel orm

Last synced: 5 months ago
JSON representation

Adds optimistic locking feature to eloquent models.

Awesome Lists containing this project

README

          

# Laravel Optimistic Locking
![Build Status](http://img.shields.io/travis/reshadman/laravel-optimistic-locking/master.png?style=flat-square)

Adds optimistic locking feature to Eloquent models.

## Installation
```bash
composer require reshadman/laravel-optimistic-locking
```

> This package supports Laravel 5.5.*, 5.6.*, 5.7.*, 5.8.*, and 6.* .

## Usage

### Basic usage
use the `\Reshadman\OptimisticLocking\OptimisticLocking` trait
in your model:

```php
integer('lock_version')->unsigned()->nullable();
```

Then you are ready to go, if the same resource is edited by two
different processes **CONCURRENTLY** then the following exception
will be raised:

```php
lock_version}}"
```
and in controller:
```php
lock_version = request('lock_version');
$post->save();
// You can also define more implicit reusable methods in your model like Model::saveWithVersion(...$args);
// or just override the default Model::save(...$args); method which accepts $options
// Then automatically read the lock version from Request and set into the model.
}
}
```

So if two authors are editing the same content concurrently,
you can keep track of your **Read State**, and ask the second
author to rewrite his changes.

### Disabling and enabling optimistic locking
You can disable and enable optimistic locking for a specific
instance:

```php
disableLocking();
$blogPost->enableLocking();
```

By default optimistic locking is enabled when you use
`OptimisticLocking` trait in your model, to alter the default
behaviour you can set the lock strictly to `false`:

```php
enableLocking();`

### Use a different column for tracking version
By default the `lock_version` column is used for tracking
version, you can alter that by overriding the following method
of the trait:

```php
where('id', $this->id)
->where('lock_version', $this->lock_version)
->update($changes);
```

If the resource has been updated before your update attempt, then the above will simply
update **no** records and it means that the model has been updated before
current attempt or it has been deleted.

### Why don't we use `updated_at` for tracking changes?
Because they may remain the same during two concurrent updates.

## Running tests
Clone the repo, perform a composer install and run:

```vendor/bin/phpunit```

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
ense (MIT). Please see License File for more information.