From 98aa74abd91eefa7fd14cc5a649a6fa264bbdf97 Mon Sep 17 00:00:00 2001 From: Misha van Tol Date: Fri, 25 Mar 2022 15:53:23 +0100 Subject: [PATCH] fix nth where step <= offset (#41645) Co-authored-by: Misha van Tol --- src/Illuminate/Collections/Collection.php | 4 ++-- src/Illuminate/Collections/LazyCollection.php | 4 ++-- tests/Support/SupportCollectionTest.php | 2 ++ 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 02d8f8925e22..61a48841c112 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -806,8 +806,8 @@ public function nth($step, $offset = 0) $position = 0; - foreach ($this->items as $item) { - if ($position % $step === $offset) { + foreach ($this->slice($offset)->items as $item) { + if ($position % $step === 0) { $new[] = $item; } diff --git a/src/Illuminate/Collections/LazyCollection.php b/src/Illuminate/Collections/LazyCollection.php index 957a1923e647..e1cdcd99d6eb 100644 --- a/src/Illuminate/Collections/LazyCollection.php +++ b/src/Illuminate/Collections/LazyCollection.php @@ -796,8 +796,8 @@ public function nth($step, $offset = 0) return new static(function () use ($step, $offset) { $position = 0; - foreach ($this as $item) { - if ($position % $step === $offset) { + foreach ($this->slice($offset) as $item) { + if ($position % $step === 0) { yield $item; } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 7fae62e4a69f..59ac9c54bbd5 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -2956,6 +2956,8 @@ public function testNth($collection) $this->assertEquals(['b', 'f'], $data->nth(4, 1)->all()); $this->assertEquals(['c'], $data->nth(4, 2)->all()); $this->assertEquals(['d'], $data->nth(4, 3)->all()); + $this->assertEquals(['c', 'e'], $data->nth(2, 2)->all()); + $this->assertEquals(['c', 'd', 'e', 'f'], $data->nth(1, 2)->all()); } /**