Skip to content

[12.x] JSON API: Deduplicate circular references #58348

Merged
taylorotwell merged 2 commits into
laravel:12.xfrom
mateusjatenee:json-resource-circular-ref
Jan 12, 2026
Merged

[12.x] JSON API: Deduplicate circular references #58348
taylorotwell merged 2 commits into
laravel:12.xfrom
mateusjatenee:json-resource-circular-ref

Conversation

@mateusjatenee

Copy link
Copy Markdown
Contributor

Branching off of #58329
The previous PR went a bit astray so I wanted to keep this one focused.

The problem: When using things like chaperone, where two models reference themselves, compileResourceRelationships will turn into an infinite loop as it adds the available relationships into the resource map. For example:

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class)->chaperone();
    }
}

class Post extends Model
{
    public function author()
    {
        return $this->belongsTo(User::class);
    }
}


class UserResource extends JsonApiResource
{
    protected array $relationships = [
        'posts' => PostResource::class,
    ];
}

class PostResource extends JsonApiResource
{
    protected array $relationships = [
        'author' => UserResource::class,
    ];
}

The following hangs:

return User::with('posts')->find(1)->toResource();

This PR fixes that by using a WeakMap to track visited object instances along with their resource type, preventing the same object from being processed multiple times. It does not handle any additional deduplication we discussed/implemented on #58329

@taylorotwell taylorotwell merged commit 7c2d679 into laravel:12.x Jan 12, 2026
69 of 70 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.

2 participants