How to get a random item from Laravel collection?
You can use the random() method to retrieve a random item from a Laravel Collection. Here's an example:
$collection = collect([1, 2, 3, 4, 5]);
$randomItem = $collection->random();
In this example, `$collection` is a Laravel Collection containing the numbers 1 through 5. The random() method is called on the collection to retrieve a random item, which is assigned to the $randomItem variable.
You can also use the `shuffle()` method to shuffle the collection and then retrieve the first item, which will be a random item from the original collection:
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$randomItem = $shuffled->first();
In this example, $collection is the same as in the previous example. The shuffle() method is called on the collection to shuffle the items randomly, and the resulting shuffled collection is assigned to the $shuffled variable. The first() method is then called on the shuffled collection to retrieve the first item, which will be a random item from the original collection.
Connect with KoderSolution 🚀
Master modern software engineering, scalable architectures, and advanced backend systems.
Read more architectural deep-dives, systems tutorials, and engineering guides on kodersolution.com.
Subscribe to @kodersolution for concise, animated system design breakdowns and technical shorts.
Follow our official page for daily development tips, architecture discussions, and community updates.
Callum Davies
PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.