Created
April 19, 2024 08:03
-
-
Save zoparga/d7c9ed34f6e31f3b78653f373cd0895c to your computer and use it in GitHub Desktop.
GenerateSafeUuidTrait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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