ItSolutionStuff.com

How to Get Random Item from Laravel Collection?

By Hardik Savani • November 5, 2023
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...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Collection keys() Method Example

Read Now →

Laravel Collection Has Method Example

Read Now →

Laravel Collection Map Method Example

Read Now →

Laravel Collection Except() Method Example

Read Now →

Laravel Collection Count and CountBy Method Example

Read Now →

Laravel Collection GroupBy with Examples

Read Now →

Laravel Collection Forget | Remove Item from Collection Laravel

Read Now →

Laravel Collection SortByDesc Tutorial with Examples

Read Now →

Laravel Collection SortBy Tutorial with Examples

Read Now →

Laravel Collection Merge | How to Merge Two Eloquent Collection?

Read Now →

Laravel Collection Unique | Remove Duplicates from Collection Laravel

Read Now →

Laravel Collection Search Method Example

Read Now →

Laravel Collection Filter Method Example

Read Now →