How to Get Random Item from Laravel Collection?

By Hardik Savani November 5, 2023 Category : Laravel

Hi,

Here, I will show you how to work how to get random item from laravel collection. step by step explain laravel collection get random item. I explained simply step by step laravel collection random. you'll learn laravel collection random element.

Laravel collection provides random() to get random item from collection in laravel. the random() method on a collection allows you to retrieve a random item (or multiple random items) from the collection. You can pass an optional argument to the random() method to specify how many random items you want to retrieve from the collection.

So, let's see the following two examples with output:

Example 1:

you can see the following controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

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

$randomItem = $collection->random();

dd($randomItem);

}

}

Output:

4

Example 2:

you can see the following controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

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

$randomItem = $collection->random(2);

dd($randomItem);

}

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => 1

[1] => 4

)

[escapeWhenCastingToString:protected] =>

)

I hope it can help you...

Shares