How to get a random item from Laravel collection?
Laravel

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.

Get The latest Coding solutions.

Subscribe to the Email Newsletter