Garry Garry - 5 months ago 24x
SQL Question

How can I select a random entry from a database using Laravel 4's Eloquent ORM?

I have an Eloquent model called

linked to a database table named

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();


$random_questions = Question::takeRandom(5)->get();


Simply you can do:

$random_question = Question::orderBy(DB::raw('RAND()'))->take(1)->get();


$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