Laravel 5

Laravel 5 Collections: Randomizing Element Order With shuffle


John Koster

Published on April 22, 2018

The shuffle method is used to rearrange the items of the array in a random distribution. The shuffle method will return a new collection and will not modify the original collection instance.


1public function shuffle(
2 $seed = null

Example Use

The following code example shows the usage of the shuffle method. The output will change each time the code is executed, so the output is unlikely to match the example output on the first try; if it does, please let me know:

1use Illuminate\Support\Collection;
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third'
8// Shuffle the collection.
9$shuffled = $collection->shuffle();

After the above code sample has executed, the $shuffled variable will be an instance of Collection and will contain a value similar to the following output (likely with a different order):

2 protected 'items' =>
3 array
4 0 => string 'third'
5 1 => string 'second'
6 2 => string 'first'