Skip to content

Commit

Permalink
Merge branch '5.5'
Browse files Browse the repository at this point in the history
  • Loading branch information
GrahamCampbell committed Nov 30, 2017
2 parents a472d71 + 5423503 commit a963c5f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,25 @@ public function first(callable $callback = null, $default = null)
return Arr::first($this->items, $callback, $default);
}

/**
* Get the first item by the given key value pair.
*
* @param string $key
* @param mixed $operator
* @param mixed $value
* @return static
*/
public function firstWhere($key, $operator, $value = null)
{
if (func_num_args() == 2) {
$value = $operator;

$operator = '=';
}

return $this->first($this->operatorForWhere($key, $operator, $value));
}

/**
* Get a flattened array of the items in the collection.
*
Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ public function testFirstWithDefaultAndWithoutCallback()
$this->assertEquals('default', $result);
}

public function testFirstWhere()
{
$data = new Collection([
['material' => 'paper', 'type' => 'book'],
['material' => 'rubber', 'type' => 'gasket'],
]);

$this->assertEquals('book', $data->firstWhere('material', 'paper')['type']);
$this->assertEquals('gasket', $data->firstWhere('material', 'rubber')['type']);
$this->assertNull($data->firstWhere('material', 'nonexistant'));
$this->assertNull($data->firstWhere('nonexistant', 'key'));
}

public function testLastReturnsLastItemInCollection()
{
$c = new Collection(['foo', 'bar']);
Expand Down

0 comments on commit a963c5f

Please sign in to comment.