Skip to content

Feature: Configurable UUID version #142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,17 @@ class Post extends Model
}
```

Alternatively, if you would like to use a different `$uuidVersion` on all of your models, then you can set the configuration setting to one of the versions outlined above. If a different `$uuidVersion` is specified on a model then this will override the global setting. Remove the ```public function uuidVersion(): string``` function from your model if it is set to take the global default.

```php
return [
/**
* The default uuid version used to generate UUID value.
*/
'uuid_version' => 'uuid4',
];
```

Whilst not recommended, if you _do_ choose to use a UUID as your primary model key (`id`), be sure to configure your model for this setup correctly. Not updating these properties will lead to Laravel attempting to convert your `id` column to an integer, which will be cast to `0`. When used in combination with the `EfficientUuid` cast, this casting will result in a `Ramsey\Uuid\Exception\InvalidUuidStringException` being thrown.

```php
Expand Down
5 changes: 5 additions & 0 deletions config/model-uuid.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@
* The default column name which should be used to store the generated UUID value.
*/
'column_name' => 'uuid',

/**
* The default uuid version used to generate UUID value.
*/
'uuid_version' => 'uuid4',
];
9 changes: 6 additions & 3 deletions src/GeneratesUuid.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,20 @@ public function resolveUuid(): UuidInterface
return call_user_func([Uuid::class, $this->resolveUuidVersion()]);
}

public function uuidVersion(): string
public function uuidVersion(): string | null
{
return 'uuid4';
return null;
}

/**
* Resolve the UUID version to use when setting the UUID value. Default to uuid4.
*/
public function resolveUuidVersion(): string
{
if (($uuidVersion = $this->uuidVersion()) === 'ordered') {

$uuidVersion = $this->uuidVersion() ?? config('model-uuid.uuid_version', 'uuid4');

if ($uuidVersion === 'ordered') {
$uuidVersion = 'uuid6';
}

Expand Down