0

I'm building a quiz application. I want the questions and the possible answers to be randomized so that when a user attempts the same quiz, he gets presented the same questions but in different order. I also want to only display one question (with possible answers) at a time and the user should be able to go back or forward through his questions.

I'm using Laravel's pagination to ensure I present a single question at a time to the user.

I have a route defined as follows:

Route::get('questions/{exam}', 'QuestionController@getSingleExam')->name('questions-exam');

In the controller I have:

public function getSingleExam(Exam $exam) {      
   $questions = Question::inRandomOrder()->where('exam_id', '=', $exam->id )->with(['options' => function($query) {
            $query->orderBy(DB::raw('RAND()'));
        }])->simplePaginate(1);

   return view('frontend.modules.question-wizard', ['questions' => $questions,'exam' => $exam]);
}

The view presents the question and the possible answers. The problem is that each time I refresh the page, I get another question (due to the randomize function). When I click the next button and go back (using the pagination arrows), I get another random question. This is due to the fact that the pagination arrows call the route again, so the random function within the controller is used.

I would want to change this behaviour and:

  • read in all the questions (and the possible answers per question) in a way that once the route is called and the page is displayed, the questions will remain in the same order whenever a user is going forward or backwards through the questions.
  • keep state of the answers, so that when a users goes back or forward, his selected answer is remembered.

I believe this means I cannot use pagination, right? Any other idea on how to accomplish this?

wiwa1978
  • 2,317
  • 3
  • 31
  • 67

0 Answers0