scramble icon indicating copy to clipboard operation
scramble copied to clipboard

Enum constraints are not added to response objects

Open manuel-watchenterprise opened this issue 1 year ago • 6 comments

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;
}

image

manuel-watchenterprise avatar Oct 28 '24 14:10 manuel-watchenterprise

@manuel-watchenterprise what is the expected result here?

romalytvynenko avatar Oct 29 '24 11:10 romalytvynenko

Something like this: image

manuel-watchenterprise avatar Oct 29 '24 12:10 manuel-watchenterprise

Something like this: image

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'),
])

image

ikhbaaalll avatar Oct 30 '24 19:10 ikhbaaalll

@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.

manuel-watchenterprise avatar Oct 30 '24 22:10 manuel-watchenterprise

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

willvincent avatar Mar 01 '25 19:03 willvincent

@manuel-watchenterprise is this still relevant for you or you use a workaround?

romalytvynenko avatar Mar 06 '25 06:03 romalytvynenko

Closing issue do to inactivity

romalytvynenko avatar Jun 30 '25 12:06 romalytvynenko