Skip to content

fix(laravel): detect enum casts in eloquent property metadata factory#8247

Merged
soyuka merged 2 commits into
api-platform:4.3from
soyuka:fix/laravel-cast-enum-8138
Jun 5, 2026
Merged

fix(laravel): detect enum casts in eloquent property metadata factory#8247
soyuka merged 2 commits into
api-platform:4.3from
soyuka:fix/laravel-cast-enum-8138

Conversation

@soyuka
Copy link
Copy Markdown
Member

@soyuka soyuka commented Jun 5, 2026

Summary

Laravel models declaring enum casts ('col' => MyEnum::class in $casts or casts()) lost enum metadata: EloquentPropertyMetadataFactory fell through to Type::string(). Downstream JSON Schema / OpenAPI / normalization saw a string, not an enum. Now resolves to Type::enum($class) when the cast target is a BackedEnum or UnitEnum, also handling Laravel's Class:param parameter syntax (e.g. AsEnumCollection:Foo).

Reproduction

A model with protected \$casts = ['status' => BookStatus::class] exposed status as a plain string in the generated schema instead of an enum.

Test plan

  • Added failing tests for backed-int, backed-string and unit enum casts.
  • Tests pass after the fix.
  • Related Laravel tests still pass locally.

Fixes #8138

soyuka added 2 commits June 5, 2026 11:03
Map Laravel enum casts (BackedEnum and UnitEnum) to Type::enum() instead
of falling back to Type::string(). Resolves missing enum schema and
normalization downstream (JsonSchema, OpenAPI) when models declare casts
via $casts or the casts() method.

Fixes api-platform#8138
PHP's ReflectionClass::newInstanceWithoutConstructor() throws \Error
(not \ReflectionException) for enums. When the GraphQl TypeConverter
resolves an enum property (e.g. an Eloquent cast to BackedEnum) it walks
the resource metadata factory chain, hitting
EloquentResourceCollectionMetadataFactory and crashing.

Guard with $refl->isEnum() before newInstanceWithoutConstructor() in
both EloquentResourceCollectionMetadataFactory and the symmetric
EloquentAttributePropertyMetadataFactory, returning the decorated
chain's result for the enum class. Adds a unit test that exercises
the path with workbench BookStatus.

Refs api-platform#8138.
@soyuka soyuka merged commit a6bdf71 into api-platform:4.3 Jun 5, 2026
109 of 112 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.

1 participant