diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php index 167998411eec..ed05d8448ef3 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -1061,14 +1061,18 @@ protected function setTimestampsOnAttach(array $record, $exists = false) /** * Detach models from the relationship. * - * @param int|array $ids + * @param mixed $ids * @param bool $touch * @return int */ public function detach($ids = [], $touch = true) { if ($ids instanceof Model) { - $ids = (array) $ids->getKey(); + $ids = $ids->getKey(); + } + + if ($ids instanceof Collection) { + $ids = $ids->modelKeys(); } $query = $this->newPivotQuery(); @@ -1079,7 +1083,7 @@ public function detach($ids = [], $touch = true) $ids = (array) $ids; if (count($ids) > 0) { - $query->whereIn($this->otherKey, (array) $ids); + $query->whereIn($this->otherKey, $ids); } // Once we have all of the conditions set on the statement, we are ready diff --git a/tests/Database/DatabaseEloquentBelongsToManyTest.php b/tests/Database/DatabaseEloquentBelongsToManyTest.php index e49663836fa0..7bcedb04a9e0 100755 --- a/tests/Database/DatabaseEloquentBelongsToManyTest.php +++ b/tests/Database/DatabaseEloquentBelongsToManyTest.php @@ -281,6 +281,27 @@ public function testDetachWithSingleIDRemovesPivotTableRecord() $this->assertTrue($relation->detach([1])); } + public function testDetachMethodConvertsCollectionToArrayOfKeys() + { + $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['touchIfTouching'], $this->getRelationArguments()); + $query = m::mock('stdClass'); + $query->shouldReceive('from')->once()->with('user_role')->andReturn($query); + $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query); + $query->shouldReceive('whereIn')->once()->with('role_id', [1, 2, 3]); + $query->shouldReceive('delete')->once()->andReturn(true); + $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass')); + $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query); + $relation->expects($this->once())->method('touchIfTouching'); + + $collection = new Collection([ + m::mock(['getKey' => 1]), + m::mock(['getKey' => 2]), + m::mock(['getKey' => 3]), + ]); + + $this->assertTrue($relation->detach($collection)); + } + public function testDetachMethodClearsAllPivotRecordsWhenNoIDsAreGiven() { $relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['touchIfTouching'], $this->getRelationArguments());