diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index 3d14d0467d9c..f28182d0f9b8 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -329,6 +329,8 @@ public static function first($array, ?callable $callback = null, $default = null */ public static function last($array, ?callable $callback = null, $default = null) { + $array = static::from($array); + if (is_null($callback)) { return empty($array) ? value($default) : array_last($array); } diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php index 67499af4ac13..0157e6909fde 100644 --- a/tests/Support/SupportArrTest.php +++ b/tests/Support/SupportArrTest.php @@ -2,6 +2,7 @@ namespace Illuminate\Tests\Support; +use ArrayIterator; use ArrayObject; use Illuminate\Support\Arr; use Illuminate\Support\Carbon; @@ -504,6 +505,15 @@ public function testLast() $this->assertEquals(200, $value5); } + public function testLastAcceptsIterables() + { + $items = new ArrayIterator(['first' => 100, 'second' => 200, 'third' => 300]); + + $this->assertSame(300, Arr::last($items)); + $this->assertSame(200, Arr::last($items, fn ($value, $key) => $key !== 'third')); + $this->assertSame('default', Arr::last(new ArrayIterator, default: 'default')); + } + public function testFlatten() { // Flat arrays are unaffected