public function index(Request $request) { /* * session()->keep here is used to retain the lesson id even if the user refreshes the page * this keeps the lesson id hidden to the user and inaccessible by anyone else * the lesson id is not retained when navigating away from the page so the page will be inaccessible once done */ $lessonId = session('lessonId'); // If lesson id does not exist in the session, do not allow access to the page if (!isset($lessonId)) { return redirect('lessons'); } $user = auth()->user(); $words = Word::orderBy(\DB::raw('RAND()'))->take(80)->get(); $questions = LessonWord::with('word')->where('lesson_id', $lessonId)->get(); session()->flash('maxQuestions', count($questions)); if (empty(session('questionIndex'))) { session()->flash('questionIndex', 0); // Start with index zero } else { session()->keep('questionIndex'); } $generatedOptions = $this->generateOptions($questions, $words); // Pass this to view if ($generatedOptions == null) { return redirect('lessons'); // Return users to lesson page if they try to go back to the finished exam } return view('lessons.exam', ['user' => $user, 'questions' => $questions, 'options' => $generatedOptions]); }