How to shuffle and paginate data with laravel

1.1k Views Asked by At

I want to shuffle and paginate data in laravel.

when I use this code :

`$questions = Question::where("exam_id",$exam->id)->shuffle()->paginate(1);`

gives me this error : BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Builder::shuffle() and when I use this code:

$questions = Question::where("exam_id",$exam->id)->paginate(1)->shuffle();

in dd($questions = Question::where("exam_id",$exam->id)->paginate(1)->shuffle());gives me a collection that has the first item and other items don't exist. And there is also no paging information.And when I don't use dd() gives me this error : Method Illuminate\Database\Eloquent\Collection::links does not exist. While I use $questions->links() in the view. When I use this code :

$questions = Question::where("exam_id",$exam->id)->get()->shuffle()->paginate(1);

Gives me this error : Method Illuminate\Database\Eloquent\Collection::paginate does not exist.

And when I use this code :

$questions = Question::where("exam_id",$exam->id)->inRandomOrder()->paginate(1);

It works, but the data is repeated on later pages. For example, the data on the first page may be repeated on page seven or other pages.

In fact, I want the data to be sorted by random And then paginated so that when a data is loaded on one page not repeated on subsequent pages.

please help me!!Thanks

1

There are 1 best solutions below

0
On

I was facing this same problem and solved it by adding the shuffle()->all() methods to the collection variable in the view file, which seems to work perfectly.

Once you pass the variable to the view to loop over using a foreach I added the following:

$rows->shuffle()->all()

So my foreach loop looks like:

foreach($rows->shuffle()->all() as $row){ ... }

The rows on the front end when loaded using ajax still work as they should with the paginator since the collection is untouched and the selection of the next rows is correctly loaded and then shuffled, meaning there are no duplicates.