2

I am getting question randomly by using the following method:

public function mcq($id)
{
    $questions = Chapter::find($id)->questions()->orderByRaw("RAND()")->paginate(1);
    return view('pages.mcq')->withQuestions($questions);
}

How can avoid repeat questions.

2
  • Unless there are duplicate questions in your database, this should return unique values. Also, paginate(1) will always return a single question, so how could there possibly be duplicates? Commented Jan 4, 2018 at 15:48
  • it means question should not repeat on all pages Commented Jan 5, 2018 at 6:18

4 Answers 4

2

You can try this inRandomOrder()

$questions = Chapter::find($id)->questions()->inRandomOrder()->get();
Sign up to request clarification or add additional context in comments.

1 Comment

It will not change anything, it's just a wrapper for orderByRaw()
1

You can't keep the same results when using random ordering.

If you really want to make it random for each user but keep paginating working, you could create a random index and keep it in the session. Something like this:

session(['random' => [[1, 18, 5], [4, 3, 8], [3, 9, 14], ....]]);

Then use it for every page:

Chapter::find(1)->questions()->whereIn('id', session('random')[$pageIndex])->get();

You'll also need to manually create a paginator.

Comments

0

You can set currently fetched questions id in a session variable as an array. Next time when you query for the question check for the session array and if it exists you can pass those ids in your query as

 ->whereNotIn('id', [1, 2, 3])

so that it won't repeat.

Comments

0

you just can't depend on eloquent to do that , you have to add a verification layer where you can store the seen question by the user in the session and then check if id isn't in that array of already seen question by using something like this

session()->put('questions', array_merge(session('questions'), $id));

and then checking

Chapter::find($id)->questions()->whereNotIn('id',session('questions'))->inRandomOrder()->get();

2 Comments

is it possible that i will submit answer and will go back on previous question page after submitting answer? because after submitting answer i want to display answer result on same page where he submitted answer and the a report option will be appear also after submitting. any idea?
Yeah ofc , you have the access of the question or the page id , so its easy to display that page again like showing , then pass a variable that has the answer , something like this return view('your question view',compact('your answer variable')); and in the view when you display the question check if there is an answer variable is set

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.