jaeyson's avatar

Pagination: Random data without repeating

hi! how do i return a random data without repeating it?

$photos = Photos::inRandomOrder()
	->where(['popular' => 'y'])
	->paginate(30)
	->onEachSide(1);

return $photos;

i had the same inquiry like this.

0 likes
11 replies
Snapey's avatar
Snapey
Best Answer
Level 122

Some previous options

https://laracasts.com/discuss/channels/eloquent/show-in-random-order-initially?page=1

perhaps remembering the ones seen already;

$photos = Photos::inRandomOrder()
	->whereNotIn('id', $request->session()->get('photos',[])
	->where(['popular' => 'y'])
	->paginate(30)
	->onEachSide(1);

if($request->has('page') {

	$request->session()->push('photos', $photos->pluck('id'));

} else {

	$request->session()->forget('photos')
}


return $photos;

So get the photos not already mentioned in the photos array and paginate them

Store the photos loaded this page into session, but only if there is a page= parameter

Something like that (untested!)

jaeyson's avatar

I tried using it inside tinker it returned RuntimeException with message 'Session store not set on request.' :\

I had \Illuminate\Session\Middleware\StartSession::class in Kernel.php and the route is not using auth

jaeyson's avatar

its working, i fetched session in view instead in controller. thank you! :)

Snapey's avatar

You don't have the request object or sessions in tinker so you cannot test it there.

jaeyson's avatar

still showing duplicated images. also foo is a seed right? it returned

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'foo' in 'order clause' (SQL: select * from `photos` where (`featured` = y) order by RAND(foo) limit 24 offset 0)
jaeyson's avatar

yeah, using inRandomOrder() alone will repeat images on pagination (calling it via ajax), i had to follow @snapey's post to store in session.

spyworld's avatar

@snapey is the best solution. Before authorization, you can store photo_id in web client cookie or session. If you're writing ajax response, store at localstorage, IndexedDB or WebSQL.

Snapey's avatar

@spyworld no, store in session. Authorization is irrelevant since you always have a session

Please or to participate in this conversation.