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

feat(Roles): Support for casting role names to enums #2616

Merged

Conversation

gajosadrian
Copy link
Contributor

@gajosadrian gajosadrian commented Feb 17, 2024

fixes #2609

It's more like a new feature because @schnetzi extended base Role model and did:

protected $casts = [
    'name' => UserRoleEnum::class,
];

I used a custom accesor to dynamically cast it into the corresponding enum. Otherwise, it returns the original name attribute value.

/**
 * @return string|\BackedEnum
 */
public function getNameAttribute()
{
    $name = $this->attributes['name'];

    if (str_contains($name, 'casted_enum')) {
        return TestRolePermissionsEnum::from($name);
    }

    return $name;
}

@gajosadrian
Copy link
Contributor Author

gajosadrian commented Feb 17, 2024

Probably need to add tests with string parameters too. Actually I don't know.. for sure it works if the given parameters are enums as well the casts.

@drbyte
Copy link
Collaborator

drbyte commented Apr 19, 2024

Thanks!

@drbyte drbyte merged commit 2c5369e into spatie:main Apr 19, 2024
22 checks passed
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.

Enums shouldn't be casted in the model
2 participants