diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 02dfa4715e99..b830635dce5a 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -995,6 +995,19 @@ public function push(...$values) return $this; } + /** + * Prepend one or more items to the beginning of the collection. + * + * @param TValue ...$values + * @return $this + */ + public function unshift(...$values) + { + array_unshift($this->items, ...$values); + + return $this; + } + /** * Push all of the given items onto the collection. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 7e2565044c72..0c5e5e6d9c93 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -3788,6 +3788,51 @@ public function testPushWithMultipleItems() $this->assertSame($expected, $actual); } + public function testUnshiftWithOneItem() + { + $expected = [ + 0 => 'Jonny from Laroe', + 1 => ['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe'], + 2 => ['a', 'b', 'c'], + 3 => 4, + 4 => 5, + 5 => 6, + ]; + + $data = new Collection([4, 5, 6]); + $data->unshift(['a', 'b', 'c']); + $data->unshift(['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe']); + $actual = $data->unshift('Jonny from Laroe')->toArray(); + + $this->assertSame($expected, $actual); + } + + public function testUnshiftWithMultipleItems() + { + $expected = [ + 0 => 'a', + 1 => 'b', + 2 => 'c', + 3 => 'Jonny', + 4 => 'from', + 5 => 'Laroe', + 6 => 'Jonny', + 7 => 'from', + 8 => 'Laroe', + 9 => 4, + 10 => 5, + 11 => 6, + ]; + + $data = new Collection([4, 5, 6]); + $data->unshift('Jonny', 'from', 'Laroe'); + $data->unshift(...[11 => 'Jonny', 12 => 'from', 13 => 'Laroe']); + $data->unshift(...collect(['a', 'b', 'c'])); + $actual = $data->unshift(...[])->toArray(); + + $this->assertSame($expected, $actual); + } + #[DataProvider('collectionClassProvider')] public function testZip($collection) {