testmonitor/eloquent-lockable

Make Eloquent models read-only after they're locked. Prevents updates and deletes based on a `locked` attribute.

dev-main 2025-04-18 13:00 UTC

This package is auto-updated.

Last update: 2025-04-18 13:00:10 UTC


README

Latest Stable Version CircleCI codecov StyleCI License

Make Laravel Eloquent models read-only after they're locked. Prevents updates and deletes based on a "locked" attribute. Includes a trait and required interface to clearly define and enforce lockable models.

Table of Contents

Installation

This package can be installed through Composer:

$ composer require testmonitor/eloquent-lockable

No need to publish anything — just use the trait and you’re good to go.

Usage

First, make sure to add a locked column to your model's table:

Schema::table('invoices', function (Blueprint $table) {
    $table->boolean('locked')->default(false);
});

Next, implement the Lockable trait and interface:

use Illuminate\Database\Eloquent\Model;
use TestMonitor\Lockable\Traits\Lockable;
use TestMonitor\Lockable\Contracts\IsLockable;

class Invoice extends Model implements IsLockable
{
    use Lockable;
}

That's it!

Locking & Unlocking

Now you can start locking and unlocking models:

$invoice->lock();
$invoice->unlock();

$invoice->isLocked();    // true or false

Exceptions

Trying to update or delete a locked model will throw a ModelLockedException.

try {
    $invoice->update(['amount' => 999]);
} catch (ModelLockedException $exception) {
    $model = $exception->getModel();
}

Temporary Locking

Temporarily lock or unlock a model using a callback:

$invoice->whileLocked(function ($model) {
    // Model is locked inside this closure
});

$invoice->whileUnlocked(function ($model) {
    // Temporarily unlocked
});

These automatically restore the original lock state — even if an exception is thrown.

Configurable Lock Column

Want to use a different column like archived or readonly?

Override the getLockColumn() method in your model:

public function getLockColumn(): string
{
    return 'archived';
}

Tests

The package contains integration tests. You can run them using PHPUnit.

$ vendor/bin/phpunit

Changelog

Refer to CHANGELOG for more information.

Contributing

Refer to CONTRIBUTING for contributing details.

Credits

License

The MIT License (MIT). Refer to the License for more information.