Search

Laravel 5 Collections: Retrieving Random Collection Elements With random

April 22, 2018 —John Koster

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 $number argument can be supplied 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, one individual item will be returned. If the $amount of items requested exceeds the total number of items in the collection, an instance of InvalidArgumentException will be thrown.

#Signature

1public function random(
2 $number = null
3);

#Example Use

The following example demonstrates the basic usage of the random method:

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second',
7 'third' => 'I am third'
8]);
9 
10// Randomly retrieve a single item.
11$random = $collection->random();
12 
13// Randomly retrieve a collection of items. The
14// returned value will be a Collection instance.
15$randomItems = $collection->random(2);

Some absolutely amazing
people

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.