diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 54689cb..f8847cd 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -1070,7 +1070,7 @@ public function put($key, $value) } /** - * Get one or more items randomly from the collection. + * Get zero or more items randomly from the collection. * * @param int|null $amount * @return mixed @@ -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." diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 5a40b19..0edced7 100644 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -911,6 +911,10 @@ public function testRandom() { $data = new Collection([1, 2, 3, 4, 5, 6]); + $random = $data->random(0); + $this->assertInstanceOf(Collection::class, $random); + $this->assertCount(0, $random); + $random = $data->random(1); $this->assertInstanceOf(Collection::class, $random); $this->assertCount(1, $random); @@ -920,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]);