How to get a random item from Laravel Collection?

Created at 08-Dec-2023 , By samar


You can get a random item from laravel collection by creating a collection using collect method and calling the random method on it. It will display a random value from the collection. You can also pass the argument to a random method which will return the specified number of values from the collection. Like if you pass 2 as an argument to the random method it will return 2 random values from the collection.

$collection = collect([1, 2, 3, 4, 5]);
$random = $collection->random();

In Laravel, collections provide a convenient way to work with arrays of data, offering various methods for manipulation and iteration. The random method is one of them which is used to retrieve a random item from the collection. In this case, it will randomly select one element from the array [1, 2, 3, 4, 5] and assign it to the variable $random.

$collection = collect([1, 2, 3, 4, 5]);
$random = $collection->random(2);
// $random is now a collection containing 2 random elements from the original collection

 

In the above code, the random method has an argument of 2. In this case, it will randomly select two elements from the array [1, 2, 3, 4, 5] and return them as a new collection.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.