Skip to content

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

License

Notifications You must be signed in to change notification settings

jangaraev/eloquent-model-advisory-lock

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

eloquent-model-advisory-lock

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());

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages