Skip to content

Commit d158526

Browse files
EnumerateValues::value() support and return negative values if exists #54910 (#57566)
* Improve the EnumerateValues::value() for returns value from first item in negative case * Improve the EnumerateValues::value() for returns value from first item in negative case * Update EnumeratesValues.php --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent 7d99c2a commit d158526

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/Illuminate/Collections/Traits/EnumeratesValues.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,11 @@ public function firstWhere($key, $operator = null, $value = null)
340340
*/
341341
public function value($key, $default = null)
342342
{
343-
if ($value = $this->firstWhere($key)) {
343+
$value = $this->first();
344+
345+
if ($value && Arr::exists($value, $key)) {
346+
return data_get($value, $key);
347+
} elseif ($value = $this->firstWhere($key)) {
344348
return data_get($value, $key, $default);
345349
}
346350

tests/Support/SupportCollectionTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,26 @@ public function testValueUsingEnum($collection)
11821182
$this->assertEquals(StaffEnum::Joe, $c->where('id', 2)->value('name'));
11831183
}
11841184

1185+
#[DataProvider('collectionClassProvider')]
1186+
public function testValueWithNegativeValue($collection)
1187+
{
1188+
$c = new $collection([['id' => 1, 'balance' => 0], ['id' => 2, 'balance' => 200]]);
1189+
1190+
$this->assertEquals(0, $c->value('balance'));
1191+
1192+
$c = new $collection([['id' => 1, 'balance' => ''], ['id' => 2, 'balance' => 200]]);
1193+
1194+
$this->assertEquals('', $c->value('balance'));
1195+
1196+
$c = new $collection([['id' => 1, 'balance' => null], ['id' => 2, 'balance' => 200]]);
1197+
1198+
$this->assertEquals(null, $c->value('balance'));
1199+
1200+
$c = new $collection([['id' => 1], ['id' => 2, 'balance' => 200]]);
1201+
1202+
$this->assertEquals(200, $c->value('balance'));
1203+
}
1204+
11851205
#[DataProvider('collectionClassProvider')]
11861206
public function testBetween($collection)
11871207
{

0 commit comments

Comments
 (0)