Skip to content

JSON:API resource collections fail for resources that wrap a non-model object #62296

Closed

Description

@FrittenKeeZ

Laravel Version

13.39.0

PHP Version

8.5.12

Database Driver & Version

n/a

Description

Since 13.39.0, returning a JsonApiResource collection whose resources wrap something other than a model or an array throws:

Error: Cannot use object of type stdClass as array
  at Illuminate/Http/Resources/DelegatesToResource.php:72

The cause is AnonymousResourceCollection::loadMissingRequestedRelationships(), added in #62152:

$this->collection->pluck('resource')->whereInstanceOf(Model::class)

pluck() reads resource through data_get(). A JsonResource implements ArrayAccess, so data_get() calls offsetExists('resource') on it, and that delegates to isset($this->resource['resource']). When the wrapped value is an object that doesn't implement ArrayAccess, PHP throws. This happens on every request, including ones with no include parameter.

A single resource wrapping the same object still works. 13.38.0 worked for both.

Reading the property instead of plucking it fixes it:

$this->collection->map(fn ($resource) => $resource->resource)->whereInstanceOf(Model::class)

Steps To Reproduce

use Illuminate\Http\Request;
use Illuminate\Http\Resources\JsonApi\JsonApiResource;

class PointResource extends JsonApiResource
{
    public function toId(Request $request): string
    {
        return (string) $this->resource->id;
    }

    public function toType(Request $request): string
    {
        return 'points';
    }

    public function toAttributes(Request $request): array
    {
        return ['x' => $this->resource->x];
    }
}

Route::get('/points', fn () => PointResource::collection([(object) ['id' => 1, 'x' => 10]]));
// Error: Cannot use object of type stdClass as array

Route::get('/point', fn () => new PointResource((object) ['id' => 1, 'x' => 10]));
// {"data":{"id":"1","type":"points","attributes":{"x":10}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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