Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

locopetey's avatar

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.

0 likes
3 replies
christopher's avatar

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();
}
zeratulmdq's avatar

How do you know if a question is T/F, multiple choice or photo compare? Do you have an specific field?

Please or to participate in this conversation.