Reputation: 2852
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
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
Reputation: 744
Yeah this should work:
$models = Model::all();
$model = $models->random();
Or even this:
$models = Model::get();
$model = $models->random();
Upvotes: 1
Reputation: 2875
$models = Model::all();
$model = Model::inRandomOrder()->get();
$models = Model::all();
$model = $models[rand(0, count($models) - 1];
Upvotes: 0