Skip to content

[Laravel] Unexpected non-iterable value for to-many relation due to snake_case attribute name #7278

@cay89

Description

@cay89

API Platform version(s) affected: 4.1.18

Description
After upgrading from version 4.1.3 to 4.1.18, a Unexpected non-iterable value for to-many relation. error occurs when calling a GetCollection endpoint.

Here is the relevant model:

#[
    ApiResource(
        uriTemplate: '/list/types',
        operations: [
            new GetCollection(
                name: 'list-types',
                parameters: [
                    new QueryParameter(
                        key: 'filter[id]',
                        filter: EqualsFilter::class,
                        property: 'id',
                    ),
                    new QueryParameter(
                        key: 'filter[key]',
                        filter: EqualsFilter::class,
                        property: 'key',
                    ),
                    new QueryParameter(
                        key: 'filter[status]',
                        filter: EqualsFilter::class,
                        property: 'status',
                    ),
                    new QueryParameter(key: 'sort', filter: SortFilter::class),
                ],
            ),
        ],
    ),
]
class ListType extends AbstractModel
{
    protected $fillable = ['key', 'status'];

    protected function casts(): array
    {
        return [
            'key' => ListTypeKey::class,
            'status' => ListTypeStatus::class,
        ];
    }

    /**
     * @return HasMany<ListItem, $this>
     */
    public function listItems(): HasMany
    {
        return $this->hasMany(ListItem::class, 'type_key', 'key');
    }
}

The exception is thrown in \ApiPlatform\Serializer\AbstractItemNormalizer::getAttributeValue():

$attributeValue = $this->propertyAccessor->getValue($object, $attribute);

if (!is_iterable($attributeValue)) {
    throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
}

In this case, $attribute is list_items, but the actual relation on the model is listItems, so $attributeValue ends up being null, triggering the exception.

This issue did not occur in version 4.1.3 — it started happening after upgrading to 4.1.18, so something must have changed in the serialization or name conversion logic since then.

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions