Skip to content

Laravel PersistProcessor always throwing error on HasMany and MorphMany relationships. #7206

Closed
@jonerickson

Description

@jonerickson

API Platform version(s) affected: 4.1.15

Description
The Laravel persist processor checks the HasMany and MorphMany relationships on L62 of ApiPlatform\Laravel\Eloquent\State\PersistProcessor. A RuntimeException is thrown if the relation is not an array. These relationships return a Collection, not an array, thus always throwing an error.

if (HasMany::class === $relation['type'] || MorphMany::class === $relation['type']) {
    $rel = $data->{$relation['name']};

    if (!\is_array($rel)) {
        throw new RuntimeException('To-Many relationship is not a collection.');
    }

    $toMany[$relation['method_name']] = $rel;
    unset($data->{$relation['name']});
    $this->relations[$relation['method_name']] = $relation['name'];
}

How to reproduce
Create a model as an ApiResource. Add a MorphMany relationship and try to create a new instance via a standard POST request.

Possible Solution
L66 should be changed to:

if (!\is_array($rel) && !\is_a($rel, Collection::class)) {
    throw new RuntimeException('To-Many relationship is not a collection.');
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions