I'm working on a multipage questionnaire, answering and going to the next page I want to get another row from my DB that hasn't been shown yet.
So after generating a random number I store that value into an array, and this array in a session Next time I'm looking for a random row I retrieve this array to search except these values stored in the array
I'll share my code and explain:
$x = $this->generateRandInt($request); // random number stored in $x
$this->qs = $request->session()->get('arrayOfQs'); // get the session
$question = Ctest::find($x['randomInt']); // here I'm simply looking for any random question
// This is the kind of approach I'm lookig for
// $question = Ctest::find($x['randomInt'])->whereNotIn('id', [$this->qs])->get();
// But I get error: Nested arrays may not be passed to whereIn method.
if ($this->qs) {
array_push($this->qs, $x['randomInt']); // I store the used random into array
$request->session()->put('arrayOfQs', $this->qs); // I store array into session
var_dump($this->qs); // array(3) { [0]=> int(1) [1]=> int(3) [2]=> int(8) }
}else{ // same actions but for the first iteration
$qs=[];
array_push($qs, $x['randomInt']);
$request->session()->put('arrayOfQs', $qs);
var_dump($qs); array(3) { [0]=> int(1) }
}
// This is my function to simply generate a random within a range
public function generateRandInt(Request $request)
{
$randomInt = mt_rand(1, 20);
return compact('randomInt');
}
What would be the best solution for this situation using Eloquent?
The documentation dictates whereNotIn('field','array')
should work but I must be missing something...
Why doesn't this work?
$question = Ctest::find($x['randomInt'])->whereNotIn('id', [$this->qs])->get();
may be something like this you can try
$alreadySelected = []
$currentSelected = Ctest::whereNotIn('id', [alreadySelected])->inRandomOrder()->get();
$alreadySelected = array_merge($alreadySelected, $currentSelected->pluk(id)->toArray());