Easily implement optimistic Eloquent model locking feature to your Laravel app.

Overview

quarks/laravel-locking

Easily implement optimistic Eloquent model locking feature to your Laravel app.

Latest Version Downloads PHP Version License

Installation

composer require quarks/laravel-locking

Usage

In your migration classes, add the version column to your table as below:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('blog_posts', function (Blueprint $table) {
        // create column for version tracking
        $table->lockVersion();
        // or to use a custom column name e.g., lock_version
        $table->lockVersion('lock_version');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('blog_posts', function (Blueprint $table) {
        $table->dropLockVersion(); // or $table->dropLockVersion('lock_version');
    });
}

Then add the LocksVersion trait your model classes as follows:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Quarks\Laravel\Locking\LocksVersion;

class BlogPost extends Model
{
    use LocksVersion;
    
    /**
     * Override the default lock version column name, optional.
     */
    protected static function lockVersionColumnName()
    {
        return 'lock_version';
    }
}

In your blade templates, include the current lock version as part of the form using the lockInput directive as below:

<form method="post">
    @lockInput($blogPost)
    
    <!-- more fields -->
</form>

In your controllers, fill the lock version from request using below helper:

namespace App\Http\Controllers;

use Quarks\Laravel\Locking\LockedVersionMismatchException;

// ... other imports

class BlogPostController extends Controller
{

    // ... more methods

    public function update(BlogPost $blogPost, BlogPostRequest $request)
    {
        $data = $request->validated();
        $blogPost->fill($data);
        $blogPost->fillLockVersion();

        try {
            $blogPost->save();
        } catch (LockedVersionMismatchException $e) {
            abort(409, 'This model was already modified elsewhere.');
        }
    }
}

Your model update can now be simply protected from concurrent updates as shown above.

License

See LICENSE file.

You might also like...
A Redis-based session handler for Magento with optimistic locking.

Cm_RedisSession A Redis-based session handler for Magento with optimistic locking. Features: Falls back to mysql handler if it can't connect to Redis.

A Redis-backed PHP session handler with optimistic locking

php-redis-session-abstract A Redis-based session handler with optimistic locking. Features: When a session's data size exceeds the compression thresho

A Symfony Feature Flag Bundle which easily allows you to configure and use your favorite feature flag provider.

Metro Markets FF Metro Markets FF is a Feature Flag Symfony Bundle. It easily allows you to configure and use your favorite feature flag provider. Ins

PHP application-level database locking mechanisms to implement concurrency control patterns.
PHP application-level database locking mechanisms to implement concurrency control patterns.

PHP DB Locker Introduction PHP application-level database locking mechanisms to implement concurrency control patterns. Supported drivers: Postgres In

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Easily exclude model entities from eloquent queries
Easily exclude model entities from eloquent queries

Laravel Excludable Easily exclude model entities from eloquent queries. This package allows you to define a subset of model entities who should be exc

Manage all your cron jobs without modifying crontab. Handles locking, logging, error emails, and more.

Jobby, a PHP cron job manager Install the master jobby cron job, and it will manage all your offline tasks. Add jobs without modifying crontab. Jobby

Easily interact and control your feature flags from Filament

Easily interact and control your feature flags from Filament

Cascading deletes for Eloquent models that implement soft deletes

Cascading soft deletes for the Laravel PHP Framework Introduction In scenarios when you delete a parent record - say for example a blog post - you may

Simple class that implement a CAPTCHA for your PHP App.

simple-captcha Simple class that implement a CAPTCHA for your PHP App. Installation Use the package manager composer to install. composer require will

Laravel-model-mapper - Map your model attributes to class properties with ease.
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

An unofficial package maintained by Salla to help developers to implement ZATCA (Fatoora) QR code easily which required for e-invoicing

ZATCA (Fatoora) QR-Code Implementation An unofficial package maintained by Salla to help developers to implement ZATCA (Fatoora) QR code easily which

An alternative Redis session handler for PHP featuring per-session locking and session fixation protection

RedisSessionHandler An alternative Redis session handler featuring session locking and session fixation protection. News phpredis v4.1.0 (released on

This is a plugin for pocketmine-mp, when locking a player's items helps players not to lose items or throw things around causing server lag.

[] LockedItem| v1.0.0 Player's item lock Features Player's item lock Players aren't afraid of losing items For Devolopers You can access to LockedItem

Enable query locking for WPGraphQL by implementing persisted GraphQL queries.
Enable query locking for WPGraphQL by implementing persisted GraphQL queries.

🔒 WP GraphQL Lock This plugin enables query locking for WPGraphQL by implementing persisted GraphQL queries. Persisted GraphQL queries allow a GraphQ

ExpressionEngine is a flexible, feature-rich, free open-source content management platform that empowers hundreds of thousands of individuals and organizations around the world to easily manage their web site.
ExpressionEngine is a flexible, feature-rich, free open-source content management platform that empowers hundreds of thousands of individuals and organizations around the world to easily manage their web site.

ExpressionEngine CMS ExpressionEngine is a mature, flexible, secure, free open-source content management system. It is beloved by designers for giving

🔥 Fire events on attribute changes of your Eloquent model

class Order extends Model { protected $dispatchesEvents = [ 'status:shipped' = OrderShipped::class, 'note:*' = OrderNoteChanged:

Cast your Eloquent model attributes to Value Objects with ease.

Laravel Value Objects Cast your Eloquent model attributes to value objects with ease! Requirements This package requires PHP = 5.4. Using the latest

Here are few exercises to practice how to implement API Security with NGINX App-Protect WAF.

api-security-lab This repo contains files for customers and partners to practice an API Security with NGINX App-Protect WAF. To demonstrate the capabi

Comments
  • Disble lock for a model

    Disble lock for a model

    First of all, thanks for the fork!

    When I try to disable the lock, the following error occurs

    PHP Fatal error:  App\\Models\\MyModel and Quarks\\Laravel\\Locking\\LocksVersion define the same property ($lockEnabled) in the composition of App\\Models\\MyModel. However, the definition differs and is considered incompatible. Class was composed in /var/www/html/app/Models/MyModel.php on line 19
    

    You should not define the protected $lockEnabled = true; property in the trait

    and then something like this

                if (!isset($this->lockEnabled) || $this->lockEnabled) {
                    $query->where(static::lockVersionColumnName(), '=', $this->currentLockVersion());
                }
    

    When the lockEnabled is not present, or is true, do you stuff, when set to false, skip

    opened by robjuz 0
Releases(1.0.1)
Owner
Quarks
Digitally transforming businesses using information technology.
Quarks
Schedule and unschedule eloquent models elegantly without cron jobs

Laravel Schedulable Schedule and Unschedule any eloquent model elegantly without cron job. Salient Features: Turn any Eloquent Model into a schedulabl

Neelkanth Kaushik 103 Dec 7, 2022
Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.

Dispatcher Dispatcher allows you to schedule your artisan commands within your Laravel project, eliminating the need to touch the crontab when deployi

Indatus 1.1k Jan 5, 2023
Manage Your Laravel Schedule From A Web Dashboard

Introduction Manage your Laravel Schedule from a pretty dashboard. Schedule your Laravel Console Commands to your liking. Enable/Disable scheduled tas

ⓒⓞⓓⓔ ⓢⓣⓤⓓⓘⓞ 1.6k Jan 5, 2023
Manage Your Laravel Schedule From A Web Dashboard

Introduction Manage your Laravel Schedule from a pretty dashboard. Schedule your Laravel Console Commands to your liking. Enable/Disable scheduled tas

ⓒⓞⓓⓔ ⓢⓣⓤⓓⓘⓞ 1.6k Jan 1, 2023
Manage your Laravel Task Scheduling in a friendly interface and save schedules to the database.

Documentation This librarian creates a route(default: /schedule) in your application where it is possible to manage which schedules will be executed a

Roberson Faria 256 Dec 21, 2022
Laravel-Tasks is a Complete Build of Laravel 5.2 with Individual User Task Lists

An app of tasks lists for each individual user. Built on Laravel 5.2, using 5.2 authentication and middleware. This has robust verbose examples using Laravel best practices.

Jeremy Kenedy 26 Aug 27, 2022
Laravel Cron Scheduling - The ability to run the Laravel task scheduler using different crons

Laravel Cron Scheduling Laravel Task Scheduling is a great way to manage the cron. But the documentation contains the following warning: By default, m

Sergey Zhidkov 4 Sep 9, 2022
Task Scheduling with Cron Job in Laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Shariful Islam 1 Oct 16, 2021
A better way to create complex batch job queues in Laravel.

Relay A better way to create complex batch job queues in Laravel. Installation composer require agatanga/relay Usage Example Let's say you have the fo

Agatanga 10 Dec 22, 2022
Redis-based session handler for Magento with optimistic locking

Cm_RedisSession A Redis-based session handler for Magento with optimistic locking. Features: Falls back to mysql handler if it can't connect to Redis.

Colin Mollenhour 216 Jan 5, 2023