Skip to content

Instantly share code, notes, and snippets.

@mattdfloyd
Created June 21, 2018 02:26
Show Gist options
  • Save mattdfloyd/87d31aa08c1c8abde8d20b635b1a9441 to your computer and use it in GitHub Desktop.
Save mattdfloyd/87d31aa08c1c8abde8d20b635b1a9441 to your computer and use it in GitHub Desktop.
Laravel's firstOrCreate race conditions
<?php
namespace App\Jobs;
use App\Product;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Redis;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class CreateProductJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** @var string */
public $uuid;
public function __construct(string $uuid)
{
$this->uuid = $uuid;
}
public function handle()
{
Redis::funnel('CreateProductJob')->limit(1)->then(function () {
Product::firstOrCreate(['uuid' => $this->uuid]);
}, function () {
$this->release(10);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment