Skip to content

Instantly share code, notes, and snippets.

@m-fi
Created November 18, 2021 23:57
Show Gist options
  • Save m-fi/afa426ea0c4d4f6e947e062b14d65ebb to your computer and use it in GitHub Desktop.
Save m-fi/afa426ea0c4d4f6e947e062b14d65ebb to your computer and use it in GitHub Desktop.
Laravel trait - generate uuid on model creation
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait GeneratesUuid
{
/**
* The default field name used to store the uuid.
*
* @var string
*/
protected string $uuidFieldNameDefault = 'uuid';
/**
* By default, should the models use an ordered uuid.
*
* @var bool
*/
protected bool $useOrderedUuidDefault = true;
/**
* Boots the trait.
*
* @return void
*/
protected static function bootGeneratesUuid(): void
{
static::creating(function ($model) {
$model->attributes[$model->getUuidFieldName()] = $model->getUuid();
});
}
/**
* Gets the field name used to store the uuid on the model.
*
* @return string
*/
protected function getUuidFieldName(): string
{
return $this->uuidFieldName ?? $this->uuidFieldNameDefault;
}
/**
* Should the model use an ordered uuid, or an unordered uuid.
*
* @return bool
*/
protected function shouldUseOrderedUuid(): bool
{
return $this->useOrderedUuid ?? $this->useOrderedUuidDefault;
}
/**
* Get a uuid for the model.
*
* @return string
*/
protected function getUuid(): string
{
return $this->shouldUseOrderedUuid()
? Str::orderedUuid()
: Str::uuid();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment