diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 908f00800e31..f8847cd68905 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1079,6 +1079,10 @@ public function put($key, $value) */ public function random($amount = null) { + if ($amount === 0) { + return new static; + } + if (($requested = $amount ?: 1) > ($count = $this->count())) { throw new InvalidArgumentException( "You requested {$requested} items, but there are only {$count} items in the collection." @@ -1089,10 +1093,6 @@ public function random($amount = null) return Arr::random($this->items); } - if ($amount === 0) { - return new static; - } - return new static(Arr::random($this->items, $amount)); } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index f4dd542c21e0..0edced72c2b5 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -924,6 +924,15 @@ public function testRandom() $this->assertCount(3, $random); } + public function testRandomOnEmptyCollection() + { + $data = new Collection(); + + $random = $data->random(0); + $this->assertInstanceOf(Collection::class, $random); + $this->assertCount(0, $random); + } + public function testRandomWithoutArgument() { $data = new Collection([1, 2, 3, 4, 5, 6]);