Skip to content

JsonApiResource not able to lazy-load relations #60121

@simon-tma

Description

@simon-tma

Laravel Version

13.9.0 and 12.58.0

PHP Version

8.5.6

Database Driver & Version

No response

Description

The documentation for JsonApiResources contains this example:

/**
 * Get the resource's relationships.
 */
public function toRelationships(Request $request): array
{
    return [
        'author' => UserResource::class,
        'comments' => fn () => CommentResource::collection(
            $request->user()->is($this->resource)
                ? $this->comments
                : $this->comments->where('is_public', true),
        ),
    ];
}

However running this results in:

Illuminate\Http\Resources\JsonApi\RelationResolver::handle(): Return value must be of type Illuminate\Database\Eloquent\Collection|Illuminate\Database\Eloquent\Model|null, Illuminate\Http\Resources\JsonApi\AnonymousResourceCollection returned

Changing the code to just return $this->comments->where('is_public', true) from the closure means there's no way to provide the resource class to use.

Steps To Reproduce

Create a JsonApi resource that uses the code in the documentation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions