November 30, 2016 —John Koster
random($amount = 1)
The random
method will retrieve a random $amount
of items from the collection. By default, the random
method will return only one item, however a different $amount
can be passed in to change the number of items returned. If the number of items returned is greater than one, a Collection
instance is returned. If the number of items returned is exactly one, the individual item will be returned. If the $amount
of items requested exceeds the total number of items in the collection, an InvalidArgumentException
will be thrown.
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 'first' => 'I am first', 8 'second' => 'I am second', 9 'third' => 'I am third'10]);11 12// Randomly retrieve a single item.13$random = $collection->random();14 15// Randomly retrieve a collection of items. The16// returned value will be a Collection instance.17$randomItems = $collection->random(2);
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.