Skip to content

[13.x] Fix findOrNew() and chunkMap() on HasManyThrough and BelongsToMany - #61855

Merged
taylorotwell merged 2 commits into
laravel:13.xfrom
xurshudyan:relation-find-or-new-chunk-map
Oct 5, 2026
Merged

taylorotwell merged 2 commits into
laravel:13.xfrom
xurshudyan:relation-find-or-new-chunk-map

Conversation

@xurshudyan

Copy link
Copy Markdown
Contributor

findOrNew() on HasManyThrough / HasOneThrough, and chunkMap() on those and on BelongsToMany, are not defined on the relation, so they get forwarded to the Eloquent builder and run as select * over the join. Columns from the intermediate or pivot table then overwrite the related model's columns.

For example:

$post = $country->posts()->findOrNew(7);

$post->id; // 2, the user's id instead of the post's
$post->title = 'Updated';
$post->save(); // updates post 2, not post 7

On BelongsToMany, chunkMap() returns models without pivot, and if the pivot table has an id column the models get the pivot row's id.

This adds findOrNew() and chunkMap() to HasOneOrManyThrough, and chunkMap() to BelongsToMany, going through the relation's own find() and chunk() the same way each() and chunk() already do (#22127).

* @template TReturn
*
* @param callable(TRelatedModel&object{pivot: TPivotModel}): TReturn $callback
* @param int $count

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Passing a negative number to $count may result in

Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1 near "offset": syntax error (SQL: select * from "users" order by "users"."id" asc offset 0)

so it might be good to type this as

Suggested change
* @param int $count
* @param non-negative-int $count

@taylorotwell
taylorotwell merged commit 13bb3ae into laravel:13.x Oct 5, 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.

3 participants