Skip to content

Commit

Permalink
[5.5] Add the power of Arr::get() to Collection get() (#22554)
Browse files Browse the repository at this point in the history
* Add the power of Arr::get()

By using Arr::get(), now It's possible to get nested value using collection get().

* Add tests

* Fix tests

* Fix code style
  • Loading branch information
nmfzone authored and taylorotwell committed Dec 28, 2017
1 parent a926eed commit 225cfa8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
6 changes: 1 addition & 5 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -642,11 +642,7 @@ public function forget($keys)
*/
public function get($key, $default = null)
{
if ($this->offsetExists($key)) {
return $this->items[$key];
}

return value($default);
return Arr::get($this->items, $key, $default);
}

/**
Expand Down
21 changes: 21 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2422,6 +2422,27 @@ public function testUnlessDefault()

$this->assertSame(['michael', 'tom', 'taylor'], $collection->toArray());
}

public function testGetNestedValue()
{
$collection = new Collection([
'foo' => [
'bar' => 'baz',
'books' => [
'Book 1',
'Book 2',
],
'todos' => [
'first' => 'Todo 1',
'second' => 'Todo 2',
],
],
]);

$this->assertEquals('baz', $collection->get('foo.bar'));
$this->assertEquals('Book 1', $collection->get('foo.books.0'));
$this->assertEquals('Todo 2', $collection->get('foo.todos.second'));
}
}

class TestSupportCollectionHigherOrderItem
Expand Down

0 comments on commit 225cfa8

Please sign in to comment.