Skip to content
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

[11.x] Introduce HasUniqueStringIds #53280

Open
wants to merge 1 commit into
base: 11.x
Choose a base branch
from

Conversation

cosmastech
Copy link
Contributor

@cosmastech cosmastech commented Oct 23, 2024

At work, we have a custom unique identifier type that we are using in place of UUIDs. (They are kind of like Amazon's ARNs).

I wanted to be able to use these as route keys, which works fine if I do something like this:

trait HasTwrnsTrait
{
    use HasUuids;

    public function newUniqueId(): string
    {
        return (string) Twrn::new();
    }

    public function resolveRouteBindingQuery($query, $value, $field = null)
    {
        if ($field && in_array($field, $this->uniqueIds()) && ! Twrn::isValid($value)) {
            throw (new ModelNotFoundException)->setModel(get_class($this), $value);
        }

        if (! $field && in_array($this->getRouteKeyName(), $this->uniqueIds()) && ! Twrn::isValid($value)) {
            throw (new ModelNotFoundException)->setModel(get_class($this), $value);
        }

        return parent::resolveRouteBindingQuery($query, $value, $field);
    }
}

This seemed a little bit cumbersome to have to duplicate the resolveRouteBindingQuery() logic only to change Str::isUuid(). Additionally, it's a maintenance burden.

The goal with this change is to make a more generalized trait which can be extended to make building custom string unique keys/routing by those custom implementations. As a bonus, this also consolidates the code between HasUlids and HasUuids.

With this change I can create a quick trait like this.

trait HasTwrnsTrait
{
    use HasUniqueStringIds;

    public function newUniqueId()
    {
        return (string) Twrn::new();
    }
  
    protected function isValidKey($value): bool
    {
        return Twrn::isValid($value);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant