8000 [9.x] Add `value()` collection method by stevebauman · Pull Request #42257 · laravel/framework · GitHub
[go: up one dir, main page]

Skip to content

[9.x] Add value() collection method #42257

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

Merged
merged 2 commits into from
May 11, 2022
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
Next Next commit
Add value() collection method
  • Loading branch information
stevebauman committed May 4, 2022
commit dc4fad14ec2367d33e1743d913a30c23b2c8bbd2
16 changes: 16 additions & 0 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,22 @@ public function firstWhere($key, $operator = null, $value = null)
return $this->first($this->operatorForWhere(...func_get_args()));
}

/**
* Get a single key's value from the first matching item in the collection.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function value($key, $default = null)
{
if ($value = $this->firstWhere($key)) {
return data_get($value, $key, $default);
}

return $default;
Copy link
Member

Choose a reason for hiding this comment

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

Is there a reason you didn't use value($default) here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Nope, I just didn’t think of it 😄

}

/**
* Determine if the collection is not empty.
*
Expand Down
20 changes: 20 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,26 @@ public function testValues($collection)
})->values()->all());
}

/**
* @dataProvider collectionClassProvider
*/
public function testValue($collection)
{
$c = new $collection([['id' => 1, 'name' => 'Hello'], ['id' => 2, 'name' => 'World']]);

$this->assertEquals('Hello', $c->value('name'));
$this->assertEquals('World', $c->where('id', 2)->value('name'));

$c = new $collection([
['id' => 1, 'pivot' => ['value' => 'foo']],
['id' => 2, 'pivot' => ['value' => 'bar']],
]);

$this->assertEquals(['value' => 'foo'], $c->value('pivot'));
$this->assertEquals('foo', $c->value('pivot.value'));
$this->assertEquals('bar', $c->where('id', 2)->value('pivot.value'));
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down
0