Skip to content

Commit

Permalink
Allow passing an array to Collection::find
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Dec 18, 2016
1 parent 733abbb commit 38bbe13
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Illuminate/Database/Eloquent/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,22 @@ class Collection extends BaseCollection implements QueueableCollection
*
* @param mixed $key
* @param mixed $default
* @return \Illuminate\Database\Eloquent\Model
* @return \Illuminate\Database\Eloquent\Model|static
*/
public function find($key, $default = null)
{
if ($key instanceof Model) {
$key = $key->getKey();
}

if (is_array($key)) {
if ($this->isEmpty()) {
return new static;
}

return $this->whereIn($this->first()->getKeyName(), $key);
}

return Arr::first($this->items, function ($model) use ($key) {
return $model->getKey() == $key;
}, $default);
Expand Down
19 changes: 19 additions & 0 deletions tests/Database/DatabaseEloquentCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,25 @@ public function testFindMethodFindsModelById()
$this->assertSame('taylor', $c->find(2, 'taylor'));
}

public function testFindMethodFindsManyModelsById()
{
$model1 = (new TestEloquentCollectionModel)->forceFill(['id' => 1]);
$model2 = (new TestEloquentCollectionModel)->forceFill(['id' => 2]);
$model3 = (new TestEloquentCollectionModel)->forceFill(['id' => 3]);

$c = new Collection;
$this->assertInstanceOf(Collection::class, $c->find([]));
$this->assertCount(0, $c->find([1]));

$c->push($model1);
$this->assertCount(1, $c->find([1]));
$this->assertCount(0, $c->find([2]));

$c->push($model2)->push($model3);
$this->assertCount(1, $c->find([2]));
$this->assertCount(2, $c->find([2, 3, 4]));
}

public function testLoadMethodEagerLoadsGivenRelationships()
{
$c = $this->getMockBuilder('Illuminate\Database\Eloquent\Collection')->setMethods(['first'])->setConstructorArgs([['foo']])->getMock();
Expand Down

0 comments on commit 38bbe13

Please sign in to comment.