I want use Ben Sampo Package for enum in laravel.
this package has a property named ‘description’ as new property.
but I can’t add extra properties(attributes) to my enums.
I want to have an enum ‘status’ that has a ‘isfinal’ attribute. to determine if this key is the final or not?
I added an ‘IsFinal’ class, to attributes folder, such as ‘description’ class.
and added two methods ‘getAttributeDescription’ and ‘getDescription’, for isFinal.
but below code returns null for "isFinal’:
$descriptionAttributes = $constReflection->getAttributes(IsFinal::class);
dd($descriptionAttributes);
while for description returns enum reflectionclass constant, and works. but not work for ‘is_final’.
I really need to add some attributes to some enums.
is there any way ?
I checked this package , too. it’s so good and really easy to add extra properties. but I need localization too, and it doesn’t have, by default.
Edit:
the enum I need, is something like this:
final class Status1 extends Enum
{
#[Color('red')]
#[Description('Initial status')]
#[IsFinal(false)]
const Initial = 1;
#[Color('blue')]
#[Description('suspended status')]
#[IsFinal(false)]
const Pending = 2;
#[Color('white')]
#[Description('completed status')]
#[IsFinal(true)]
const Completed = 3;
#[Color('red')]
#[Description('canceled status')]
#[IsFinal(true)]
const Canceled = 4;
}
2
Answers
For BenSampo Package, you can follow a way like this:
Create a Trait:
Create an Enum (I usually do enum values with numeric and variable names with snake case. You can customize the methods according to you):
Make sure you use
GetEnumDescription
Trait. Example instances:Example:
Result:
The BenSampo Laravel Enum package is fantastic for setting up enums with ease in Laravel. However, adding additional custom attributes can be a bit tricky, as it’s not natively supported in the package at the moment.
Here are a couple of possible approaches to achieve your goal:
You can extend the base Enum class to support additional attributes. However, this requires modifying the Enum class itself, which might not be ideal if you’re working in a team or planning on updating the package in the future.
And then use this base class for your enums:
With the above method, you can now check if an enum value is final or not:
Another approach could be to create separate Enums for these special cases. For example, you can have FinalStatus enum class for statuses that are final.
You can then use Laravel’s localization features to handle the localization of your enums. You would create language files for each language you want to support, and use the __() function in your application code to retrieve the localized string.
In any case, the cleanest solution would be to have the package support additional attributes natively. You might consider creating an issue or a pull request on the package’s GitHub repository to see if the maintainers would be open to such a feature.