laravel-enum: BadMethodCallException with numerical enum values
I have a UserTypeEnum
with 2 values, Provider and Client. I had already created the database schema with tiny integers for this field so I wanted to set the values to be numerical.
I could not see an example in the documentation for this package but I saw an example of using numbers in the base enum package.
My class is below. When I call the request transformation function, it throws a BadMethodCallException which I think is because of the strict comparison between values. My form is a simple POST form which is submitting a string "1"
which does not match the numerical 1
in the values array.
The error is as follows:
BadMethodCallException
There's no value 1 defined for enum App\Enums\UserTypeEnum, consider adding it in the docblock definition.
Enum example:
/**
* @method static self PROVIDER()
* @method static self CLIENT()
*/
final class UserTypeEnum extends Enum
{
protected static function values(): array
{
return [
'PROVIDER' => 1,
'CLIENT' => 2,
];
}
}
This is how I am calling the transformEnums method.
$request->transformEnums($this->enumCastRules());
Below is the enum cast rules I am using.
private function enumCastRules()
{
return [
'type' => UserTypeEnum::class,
];
}
My form field:
<input type="radio" name="type" id="type_provider" value="{{ \App\Enums\UserTypeEnum::PROVIDER() }}">
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 7
- Comments: 23
Commits related to this issue
- handle enum value type juggling as PHP native enums do fixes https://github.com/spatie/laravel-enum/issues/57 — committed to spatie/enum by Gummibeer 3 years ago
Can confirm that after upgrading to spatie/enum 3.10 I no longer need to override the Enum class’ constructor. Thanks @Gummibeer !
I will take care of this one today. #hacktoberfest 🎃
I’ve had the BadMethodCallException issue as well, but under a slightly different circumstance.
I store the enum values as integers in db and cast to enum in the model. All works well in mysql, but sqlite/pdo returns my integers as strings when I test, which causes the exception. My solution is to use mysql during tests, but that is obviously less than ideal. This is a clearly a sqlite/pdo limitation, but thought I should add to the conversation.
Glad the quick fix/workaround works. 🎉 The package provided one will take some more time.
Ah you are correct, I cast the raw value on the request to be an integer first and it worked now.
You can use integers - but have to properly cast the raw value before it’s passed to the enum. That’s the step I think about how to solve but I fear that there’s not an easy solution.