How to get a random item from Laravel collection?

Avatar
C

Callum Davies

Senior Backend Engineer••
8345Views
5mRead
0Reactions

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.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?
Callum Davies
C
Written by•Senior Backend Engineer

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.

React to this article

Recommended Articles

View all articles