How to Get Random Item from Laravel Collection?
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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Collection keys() Method Example
- Laravel Collection Has Method Example
- Laravel Collection Map Method Example
- Laravel Collection Except() Method Example
- Laravel Collection Count and CountBy Method Example
- Laravel Collection GroupBy with Examples
- Laravel Collection Forget | Remove Item from Collection Laravel
- Laravel Collection SortByDesc Tutorial with Examples
- Laravel Collection SortBy Tutorial with Examples
- Laravel Collection Merge | How to Merge Two Eloquent Collection?
- Laravel Collection Unique | Remove Duplicates from Collection Laravel
- Laravel Collection Search Method Example
- Laravel Collection Filter Method Example