Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.4] fix eloquent collection contains issue #19568

Merged
merged 3 commits into from
Jun 12, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 6 additions & 1 deletion src/Illuminate/Database/Eloquent/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,12 @@ 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->getKey() == $key->getKey() &&
get_class($model) == get_class($key);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use $model->is($key) instead if possible? That has some additional checks such as connection as well!

Copy link
Contributor Author

@storyn26383 storyn26383 Jun 12, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for advice, much better now 😜

});
}

return parent::contains(function ($model) use ($key) {
return $model->getKey() == $key;
Expand Down
12 changes: 12 additions & 0 deletions tests/Database/DatabaseEloquentCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,18 @@ public function testContainsIndicatesIfModelInArray()
$this->assertFalse($c->contains($mockModel3));
}

public function testContainsIndicatesIfDiffentModelInArray()
{
$mockModelFoo = m::namedMock('Foo', 'Illuminate\Database\Eloquent\Model');
$mockModelFoo->shouldReceive('getKey')->andReturn(1);
$mockModelBar = m::namedMock('Bar', 'Illuminate\Database\Eloquent\Model');
$mockModelBar->shouldReceive('getKey')->andReturn(1);
$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