PHPackages                             kevjo/laravel-collab - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. kevjo/laravel-collab

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

kevjo/laravel-collab
====================

Real-time collaborative editing for Laravel with intelligent locking and conflict resolution.

v0.2.0(4mo ago)10MITPHPPHP ^8.5CI passing

Since Feb 15Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/kevvjoo/laravel-collab)[ Packagist](https://packagist.org/packages/kevjo/laravel-collab)[ RSS](/packages/kevjo-laravel-collab/feed)WikiDiscussions main Synced today

READMEChangelog (2)Dependencies (8)Versions (6)Used By (0)

Laravel Collab
==============

[](#laravel-collab)

[![Latest Version](https://camo.githubusercontent.com/2629ab38c11cf3e7a9c089063ed1716b73ccaedf354df4fca07863b8f9f8b776/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b65766a6f2f6c61726176656c2d636f6c6c61622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kevjo/laravel-collab)[![Tests](https://github.com/kevvjoo/laravel-collab/workflows/Tests/badge.svg)](https://github.com/kevvjoo/laravel-collab/actions)[![Total Downloads](https://camo.githubusercontent.com/b4d0f4b8a16963540dfd06821be4faac8d6143b8b40a1dee059a42ccee038304/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6b65766a6f2f6c61726176656c2d636f6c6c61622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kevjo/laravel-collab)[![License](https://camo.githubusercontent.com/08116deb5e1cb60a62a8bb2cae5bda67ae80916a1cbc26d21674cdff51379792/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6b65766a6f2f6c61726176656c2d636f6c6c61622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kevjo/laravel-collab)

Pessimistic locking for Laravel Eloquent models. Prevent multiple users from editing the same record simultaneously.

Requirements
------------

[](#requirements)

- PHP 8.5+
- Laravel 12+
- MySQL 8+ or PostgreSQL (required for row-level locking via `lockForUpdate()`)

> **Note:** SQLite works for development/testing but does not support row-level locking. Race condition protection requires MySQL or PostgreSQL in production.

Installation
------------

[](#installation)

```
composer require kevjo/laravel-collab
```

Run the install command:

```
php artisan collab:install
```

This publishes the config file, migrations, and runs the migrations.

Quick Start
-----------

[](#quick-start)

### 1. Add the Trait to Your Model

[](#1-add-the-trait-to-your-model)

```
use Kevjo\LaravelCollab\Traits\HasConcurrentEditing;

class Post extends Model
{
    use HasConcurrentEditing;
}
```

### 2. Acquire and Release Locks

[](#2-acquire-and-release-locks)

```
// Acquire a lock
$result = $post->acquireLock(auth()->user());

if ($result->isFailed()) {
    return back()->with('error',
        "This post is being edited by {$result->getLockedBy()->name}"
    );
}

// Release a lock
$post->releaseLock(auth()->user());

// Lock is also auto-released after model update (configurable)
$post->update($request->validated());
```

### 3. Check Lock Status

[](#3-check-lock-status)

```
$post->isLocked();                          // Is it locked by anyone?
$post->isLockedByUser(auth()->user());      // Is it locked by me?
$post->isLockedByAnother(auth()->user());   // Is it locked by someone else?
$post->lockOwner();                         // Get the User who holds the lock
$post->lockExpiresAt();                     // Carbon instance of expiration
$post->lockRemainingTime();                 // Seconds until expiration
```

Middleware
----------

[](#middleware)

The package provides a `collab.lock` middleware that returns HTTP 423 (Locked) when a route-bound model is locked by another user.

```
// Specify which route parameter to check
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->middleware('collab.lock:post');

// Auto-detect all lockable models on the route
Route::put('/posts/{post}', [PostController::class, 'update'])
    ->middleware('collab.lock');
```

The middleware:

- Returns **423 Locked** with lock info if the model is locked by another user
- Passes through if the model is unlocked or locked by the current user
- Skips the check entirely if no user is authenticated

Configuration
-------------

[](#configuration)

Publish the config:

```
php artisan vendor:publish --tag=collab-config
```

```
// config/collab.php
return [
    'default_strategy' => 'pessimistic',

    'lock_duration' => [
        'default' => 3600,  // 1 hour
        'min'     => 60,    // 1 minute minimum
        'max'     => 86400, // 24 hours maximum
    ],

    'auto_release_after_update' => true,  // Release lock when model is updated
    'prevent_update_if_locked'  => true,  // Throw exception if locked by another

    'tables' => [
        'locks'   => 'model_locks',
        'history' => 'model_lock_history',
    ],

    'history' => [
        'enabled'        => true,
        'retention_days' => 30,
    ],
];
```

Lock Options
------------

[](#lock-options)

```
// Custom duration
$post->acquireLock($user, ['duration' => 600]); // 10 minutes

// Field-level locking
$post->acquireLock($user, ['fields' => ['title', 'content']]);

// Check field-level locks
$post->isFieldLocked('title'); // true
$post->getLockedFields();      // ['title', 'content']

// Custom metadata
$post->acquireLock($user, ['metadata' => ['reason' => 'bulk update']]);
```

Lock Management
---------------

[](#lock-management)

```
// Extend a lock
$post->extendLock(1800, $user); // 30 more minutes

// Force release (admin use)
$post->forceReleaseLock();

// Request lock from owner (fires LockRequested event)
$post->requestLock($requester);

// Get structured lock info for API responses
$post->getLockInfo();
// Returns: ['is_locked' => true, 'locked_by' => [...], 'expires_at' => '...', ...]

$post->getLockStatus($user);
// Returns: ['is_locked' => true, 'can_edit' => false, 'is_owner' => false, ...]
```

Facade
------

[](#facade)

The `Collab` facade provides system-wide lock management:

```
use Kevjo\LaravelCollab\Facades\Collab;

// Query locks
Collab::activeLocks();
Collab::expiredLocks();
Collab::getLocksFor($post);
Collab::getActiveLockFor($post);
Collab::isModelLocked(Post::class, 1);
Collab::getLocksForModelType(Post::class);

// Bulk operations
Collab::releaseAllLocksForUser($userId);
Collab::releaseAllLocks();

// Cleanup
Collab::cleanupExpiredLocks();
Collab::cleanupOldHistory();
Collab::runCleanup();

// History
Collab::getHistoryFor($post);
Collab::getUserHistory($userId);

// Stats
Collab::getStatistics();
```

Events
------

[](#events)

All events are in the `Kevjo\LaravelCollab\Events` namespace:

EventFired WhenProperties`LockAcquired`Lock is successfully acquired`$model`, `$lock`, `$user``LockReleased`Lock is released by owner`$model`, `$user``LockForceReleased`Lock is force-released (admin)`$model`, `$lockOwner`, `$releasedBy``LockRequested`User requests lock from owner`$model`, `$requester`, `$lockOwner``LockExpired`Expired lock is cleaned up`$model`, `$lock`Listen to events in your `EventServiceProvider` or with closures:

```
use Kevjo\LaravelCollab\Events\LockRequested;

Event::listen(LockRequested::class, function (LockRequested $event) {
    $event->lockOwner->notify(new LockRequestNotification(
        $event->requester,
        $event->model
    ));
});
```

Artisan Commands
----------------

[](#artisan-commands)

```
# Clean up expired locks
php artisan collab:cleanup

# Clean up expired locks + old history
php artisan collab:cleanup --all

# Preview what would be deleted
php artisan collab:cleanup --dry-run

# Install the package
php artisan collab:install
```

Add to your scheduler for automatic cleanup:

```
// app/Console/Kernel.php
$schedule->command('collab:cleanup')->hourly();
```

Automatic Behaviors
-------------------

[](#automatic-behaviors)

The trait hooks into Eloquent model events:

- **Before update:** If `prevent_update_if_locked` is `true` and the model is locked by another user, a `ModelLockedException` (HTTP 423) is thrown.
- **After update:** If `auto_release_after_update` is `true`, the lock is automatically released.
- **On delete:** All locks on the model are released with history entries created.

Testing
-------

[](#testing)

```
composer test
```

Credits
-------

[](#credits)

- [Kevin Jonathan](https://github.com/kevvjoo)

License
-------

[](#license)

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

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance75

Regular maintenance activity

Popularity2

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

138d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d969607bde45c12b2b119d2d35ca9d4167aaef3620eecfc53416b826b1cb3f81?d=identicon)[kevvjoo](/maintainers/kevvjoo)

---

Top Contributors

[![kevvjoo](https://avatars.githubusercontent.com/u/81075629?v=4)](https://github.com/kevvjoo "kevvjoo (18 commits)")

---

Tags

laravelreal-timelockingcollaborationlaravel12php85pessimistic-lockingconcurrent-editingoptimistic-locking

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/kevjo-laravel-collab/health.svg)

```
[![Health](https://phpackages.com/badges/kevjo-laravel-collab/health.svg)](https://phpackages.com/packages/kevjo-laravel-collab)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M132](/packages/laravel-pulse)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M194](/packages/laravel-ai)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[flarum/core

Delightfully simple forum software.

201.4M2.3k](/packages/flarum-core)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
