Skip to content

Instantly share code, notes, and snippets.

@talha08
Last active August 5, 2017 15:21
Show Gist options
  • Save talha08/77fb618a5be6d3bc907434cca509911f to your computer and use it in GitHub Desktop.
Save talha08/77fb618a5be6d3bc907434cca509911f to your computer and use it in GitHub Desktop.
Simply you can do:
......................
$random_question = Question::orderBy(DB::raw('RAND()'))->take(1)->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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment