Enum constraints are not added to response objects
Enum constraints (not backed!) are working fine for request objects, however, are not added to responses. Backed enums are working fine in responses as well.
/**
* @mixin \App\Models\WatchCollectionItem
*/
class WatchResource extends BaseJsonResource
{
public function toArray($request): array
{
return [
/** @var OwnershipState */
'ownership_state' => $this->ownership_state?->name,
];
}
}
class WatchCollectionItem extends Model
{
public function casts(): array
{
return [
'ownership_state' => OwnershipState::class,
];
}
}
enum OwnershipState
{
case OWNING;
case SOLD;
case TRADED;
case GIFTED;
case LOST;
}
@manuel-watchenterprise what is the expected result here?
Something like this:
Something like this:
you need to specify the value
enum MaritalEnum: string
{
case Married = "Married";
case Single = "Single";
case Widow = "Widow";
case Widowr = "Widowr";
}
$this->mergeWhen(collect($this->resource)?->get('marital') != null, [
/** @var MaritalEnum */
'marital' => collect($this->resource)?->get('marital'),
])
@ikhbaaalll thank you, I do appreciate. Though I am aware that backed enums are working fine, this is why I reported that non-backed enums are not working as - in my opinion - expected. In requests both of them are recognised and handled, however, in responses backed enums only.
I could easily and quickly refactor my non-backed enums, I might will do that, but I believe these have to be handled. It's personal taste, but having backed enum just to have identical string value assigned to value as the name is, seems unnecessary to me.
This seems to be functioning as expected.
Not sure why you'd expect a non-backed Enum to get cast to a string.
With your code...
(string) OwnershipState::OWNING
Will throw Exception Object of class OwnershipState could not be converted to string
@manuel-watchenterprise is this still relevant for you or you use a workaround?
Closing issue do to inactivity
