Skip to content

[13.x] Include identical BelongsToMany resources once in JSON:API compound documents - #62360

Merged
taylorotwell merged 2 commits into
laravel:13.xfrom
tomasvanrijsse:json-api-dedupe-belongs-to-many
Nov 7, 2026
Merged

taylorotwell merged 2 commits into
laravel:13.xfrom
tomasvanrijsse:json-api-dedupe-belongs-to-many

Conversation

@tomasvanrijsse

Copy link
Copy Markdown
Contributor

A BelongsToMany include gets a random _uniqueKey, so included can never deduplicate it. When several primary resources share the same related model, included repeats that model once for every primary resource:

GET /budgets?include=allowedUsers   // 20 budgets, all shared with the same 3 users

returns 60 user objects in included instead of 3. The JSON:API spec says a compound document must not include more than one resource object for each type and id pair.

The random key exists so that the same model with different pivot data is not collapsed into one object (covered by testItCanGenerateJsonApiResponseWithRelationshipsUsingSparseIncluded). This PR keeps that, but replaces the random part of the key with a hash of the resolved resource object. Objects that differ, for example in pivot data, still get their own entry. Byte-identical objects are included once.

The new test attaches one team to two users and requests fields[teams]=name. It fails on 13.x (the team appears twice) and passes with this change. The existing JSON:API tests pass unchanged.

@taylorotwell
taylorotwell merged commit aca3cc2 into laravel:13.x Nov 7, 2026
62 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