Quiz - Random question types I have a database for a quiz that has 3 different question types (true/false, multiple choice, photo compare). Right now I'm pulling a random 3 questions regardless of type like this:
$questions = Question::with('answers')->orderByRaw("RAND()")->take(3)->get();
Works great but the problem is sometimes I get all T/F. I would like to pull a random one from each type so I always have one of each type.
And help would be fantastic.
What about:
$question = Question::all()->toArray();
$result = array_rand($question);
$question[$result];
To make the query even cleaner you could pass this code to your Model e.g
Question.php
public function random()
{
$question = Question::all()->toArray();
$result = array_rand($question, 3);
return $question[$result];
}
And in your Controller just call the function
public function question(Question $question)
{
return $question->random();
}
@christopher I need to get the answers associated with each question as well.
How do you know if a question is T/F, multiple choice or photo compare? Do you have an specific field?
Please sign in or create an account to participate in this conversation.