I have an Eloquent model called Question
linked to a database table named questions
.
Is there an Eloquent function that will let me take a single random question (or a set number of random questions) from the database? Something like the following:
$random_question = Question::takeRandom(1)->get();
or
$random_questions = Question::takeRandom(5)->get();
Simply you can do:
$random_question = Question::orderBy(DB::raw('RAND()'))->take(1)->get();
and
$random_question = Question::orderBy(DB::raw('RAND()'))->take(5)->get();
If you want to use the syntax as you specified in your question, you can use scopes.
In the model Question
you can add the following method:
public function scopeTakeRandom($query, $size=1)
{
return $query->orderBy(DB::raw('RAND()'))->take($size);
}
Now you can do $random_question = Question::takeRandom(1)->get();
and get 1 random question.
You can read more about Laravel 4 query scopes at http://laravel.com/docs/eloquent#query-scopes