Skip to content

Commit

Permalink
[5.4] fix eloquent collection contains issue (#19568)
Browse files Browse the repository at this point in the history
* fix eloquent collection contains issue

* use $model->is($key) instead

* remove useless code
  • Loading branch information
storyn26383 authored and taylorotwell committed Jun 12, 2017
1 parent 11fe874 commit 3cde539
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
6 changes: 5 additions & 1 deletion src/Illuminate/Database/Eloquent/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,11 @@ public function contains($key, $operator = null, $value = null)
return parent::contains(...func_get_args());
}

$key = $key instanceof Model ? $key->getKey() : $key;
if ($key instanceof Model) {
return parent::contains(function ($model) use ($key) {
return $model->is($key);
});
}

return parent::contains(function ($model) use ($key) {
return $model->getKey() == $key;
Expand Down
23 changes: 20 additions & 3 deletions tests/Database/DatabaseEloquentCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,35 @@ public function testContainsWithMultipleArguments()
public function testContainsIndicatesIfModelInArray()
{
$mockModel = m::mock('Illuminate\Database\Eloquent\Model');
$mockModel->shouldReceive('getKey')->andReturn(1);
$mockModel->shouldReceive('is')->with($mockModel)->andReturn(true);
$mockModel->shouldReceive('is')->andReturn(false);
$mockModel2 = m::mock('Illuminate\Database\Eloquent\Model');
$mockModel2->shouldReceive('getKey')->andReturn(2);
$mockModel2->shouldReceive('is')->with($mockModel2)->andReturn(true);
$mockModel2->shouldReceive('is')->andReturn(false);
$mockModel3 = m::mock('Illuminate\Database\Eloquent\Model');
$mockModel3->shouldReceive('getKey')->andReturn(3);
$mockModel3->shouldReceive('is')->with($mockModel3)->andReturn(true);
$mockModel3->shouldReceive('is')->andReturn(false);
$c = new Collection([$mockModel, $mockModel2]);

$this->assertTrue($c->contains($mockModel));
$this->assertTrue($c->contains($mockModel2));
$this->assertFalse($c->contains($mockModel3));
}

public function testContainsIndicatesIfDiffentModelInArray()
{
$mockModelFoo = m::namedMock('Foo', 'Illuminate\Database\Eloquent\Model');
$mockModelFoo->shouldReceive('is')->with($mockModelFoo)->andReturn(true);
$mockModelFoo->shouldReceive('is')->andReturn(false);
$mockModelBar = m::namedMock('Bar', 'Illuminate\Database\Eloquent\Model');
$mockModelBar->shouldReceive('is')->with($mockModelBar)->andReturn(true);
$mockModelBar->shouldReceive('is')->andReturn(false);
$c = new Collection([$mockModelFoo]);

$this->assertTrue($c->contains($mockModelFoo));
$this->assertFalse($c->contains($mockModelBar));
}

public function testContainsIndicatesIfKeyedModelInArray()
{
$mockModel = m::mock('Illuminate\Database\Eloquent\Model');
Expand Down

0 comments on commit 3cde539

Please sign in to comment.