diff --git a/src/Relations/BelongsToMany.php b/src/Relations/BelongsToMany.php index 2bd74b8db..08e7ac984 100644 --- a/src/Relations/BelongsToMany.php +++ b/src/Relations/BelongsToMany.php @@ -117,6 +117,8 @@ public function sync($ids, $detaching = true) if ($ids instanceof Collection) { $ids = $ids->modelKeys(); + } elseif ($ids instanceof Model) { + $ids = $this->parseIds($ids); } // First we need to attach any of the associated models that are not currently diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index 156e656bd..b087ca481 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -255,6 +255,36 @@ public function testBelongsToMany(): void $this->assertCount(1, $client->users); } + public function testSyncBelongsToMany() + { + $user = User::create(['name' => 'John Doe']); + + $first = Client::query()->create(['name' => 'Hans']); + $second = Client::query()->create(['name' => 'Thomas']); + + $user->load('clients'); + self::assertEmpty($user->clients); + + $user->clients()->sync($first); + + $user->load('clients'); + self::assertCount(1, $user->clients); + self::assertTrue($user->clients->first()->is($first)); + + $user->clients()->sync($second); + + $user->load('clients'); + self::assertCount(1, $user->clients); + self::assertTrue($user->clients->first()->is($second)); + + $user->clients()->syncWithoutDetaching($first); + + $user->load('clients'); + self::assertCount(2, $user->clients); + self::assertTrue($user->clients->first()->is($first)); + self::assertTrue($user->clients->last()->is($second)); + } + public function testBelongsToManyAttachesExistingModels(): void { $user = User::create(['name' => 'John Doe', 'client_ids' => ['1234523']]);