Created
November 18, 2021 23:57
-
-
Save m-fi/afa426ea0c4d4f6e947e062b14d65ebb to your computer and use it in GitHub Desktop.
Laravel trait - generate uuid on model creation
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\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