jangaraev/eloquent-model-advisory-lock

Handy approach to avoid race conditions when doing upserts in Laravel Eloquent models

Installs: 116

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 1

pkg:composer/jangaraev/eloquent-model-advisory-lock

0.91 2024-09-25 11:12 UTC

This package is auto-updated.

Last update: 2025-10-25 13:33:28 UTC


README

Often you face the race conditions error when working with DB-intensive operations.

This package contains a trait with the method which helps to avoid that.

Usage

First do reference the trait in your model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Jangaraev\EloquentModelAdvisoryLock\AppliesAdvisoryLock;

class Foo extends Model
{
    use AppliesAdvisoryLock;
    
    // ...
}

This trait introduces the advisoryLock() method which receives a callable to execute.

You then can use this method to wrap your DB intensive calls.

// wrap you DB-intensive operations as a callable to the advisoryLock call
static::advisoryLock(fn () => $this->coolRelationship()->firstOrCreate());