Jared Chu
Jared Chu

Reputation: 2852

Eloquent - Random from a existing list

I see that I can get a random row in Laravel 5 by:

Model::inRandomOrder()->get();

But I want to get all from Model and pick a random object from it like below.

$models = Model::all();
$model = $models->getRandom();

Any suggestion?

Upvotes: 0

Views: 206

Answers (3)

MusheAbdulHakim
MusheAbdulHakim

Reputation: 364

Using array_rand function in php. array_rand

$models = Model::all()->toArray();
$id= array_rand(Model::all()->toArray()); //this will return the id of a random element in the array
$model = Model::findOrFail($id);

Upvotes: 0

Omar Tarek
Omar Tarek

Reputation: 744

Yeah this should work:

$models = Model::all();
$model = $models->random();

Or even this:

$models = Model::get();
$model = $models->random();

Upvotes: 1

am05mhz
am05mhz

Reputation: 2875

two sugestions:

1. get your data twice:

 $models = Model::all();
 $model = Model::inRandomOrder()->get();

2. select a random row from the retrieved data:

 $models = Model::all();
 $model = $models[rand(0, count($models) - 1];

Upvotes: 0

Related Questions