Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions tests/RelationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']]);
Expand Down