Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sefran's avatar

Laravel 5.2 - inRandomOrder() and pagination: is there an alternative to orderBy(DB::raw('RAND(aseed)')

I have to display posts on multiple pages, but I want the order be always different. Unfortunately inRandomOrder() can give already displayed items by requesting another page.

orderBy(DB::raw('RAND(aseed)') or orderByRaw('RAND(aseed)') are database specific and slow on a big dataset.

What could be an efficient alternative?

0 likes
2 replies
rdelorier's avatar
Level 9

Maybe something like this

  • get all post ids
  • shuffle and cache id list
  • use pagination with cache key
sefran's avatar

In this way I have to access the database a first time to get ids under certain conditions and then after shuffling and caching the id list, retrieve all the info (basically the same of the first query) for each id. I thought to resolve by caching the whole first query result and then use it for pagination, but it seems I cannot use closure inside Cache::remember

Please or to participate in this conversation.