Skip to content

Instantly share code, notes, and snippets.

@zoparga
Created April 19, 2024 08:03
Show Gist options
  • Save zoparga/d7c9ed34f6e31f3b78653f373cd0895c to your computer and use it in GitHub Desktop.
Save zoparga/d7c9ed34f6e31f3b78653f373cd0895c to your computer and use it in GitHub Desktop.
GenerateSafeUuidTrait
<?php
namespace App\Traits;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
trait GenerateSafeUuidTrait
{
public static function bootHasUuid()
{
static::creating(function ($model) {
// INIT INFOS
$uuid = null;
$uuidExists = true;
// GENERATE & CHECK IF UUID EXISTS
while ($uuidExists) {
$uuid = Str::uuid();
$uuidExists = DB::table($model->table)->where('uuid', '=', $uuid)->exists();
}
// USE THE CHECKED UUID
$model->uuid = $uuid;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment