Skip to content

[11.x] Add support for syncing associations with array or base collection of models#53495

Merged
taylorotwell merged 3 commits into
laravel:11.xfrom
diaafares:support-syncing-associations-with-array-of-models
Nov 14, 2024
Merged

[11.x] Add support for syncing associations with array or base collection of models#53495
taylorotwell merged 3 commits into
laravel:11.xfrom
diaafares:support-syncing-associations-with-array-of-models

Conversation

@diaafares

@diaafares diaafares commented Nov 13, 2024

Copy link
Copy Markdown
Contributor

During a code review for a teammate’s automated tests, I proposed the following change:

$tag = Tag::create([‘name’ => Str::random()]);
$tag2 = Tag::create([‘name’ => Str::random()]);

- $post->tags()->sync([$tag->id, $tag2->id]);
+ $post->tags()->sync([$tag, $tag2]);

However, he encountered an error when attempting to implement this change, despite I was very sure that I used sync with models before.

It appears that the current implementation of parseIds doesn't support passing models unless they are passed inside an Eloquent collection, so, to make it consistent, I updated the implementation to work with an array or base collection of models.

This will also be beneficial for situations when you already have an array of models:

- $post->tags()->sync(Arr::pluck($tags, 'id'));
+ $post->tags()->sync($tags);

Furthermore, it seems that there are currently no tests that cover the scenario of passing an Eloquent collection to the sync method, so I added a check for it inside my newly added test.

@taylorotwell taylorotwell merged commit fac702d into laravel:11.x Nov 14, 2024
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