PASSWORD RESET

Your destination for complete Tech news

How to get a random item from Laravel Collection?

5.5K 0
< 1 min read

To get a random item from a Laravel collection, you can use the random method. This method will return a random element from the collection, or null if the collection is empty.

Here’s an example:

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

// $random is now a random element from the collection

You can also pass a number as an argument to the random method to get that number of random elements from the collection:

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

// $random is now a collection containing 2 random elements from the original collection

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.