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

boyjarv's avatar

show in random order initially

Here is my code at the moment which randomly generates my gallery every time I paginate through my results

$artworks = Gallery::inRandomOrder()->paginate(50);

I would like to show my results in a random order only on page load not when paging through the results

0 likes
7 replies
boyjarv's avatar

thanks but now I'm getting: Method Illuminate\Database\Eloquent\Collection::links does not exist

boyjarv's avatar

Thanks but how can I use lodash shuffle in my laravel project?

Snapey's avatar

Just explaining for others.....

The problem is that you will get the first 50 in random order, then on page 2, you will get them all in random order again, which could include some of the ones already seen on the first page.

willvincent's avatar

links doesn't exist if you don't paginate. Probably what you want is to determine if something other than the first page is being requested, and only optionally use the inRandomOrder()

Snapey's avatar

I have a complicated solution and a simple solution.

Complicated

  • if no set already stored
  • Get all IDs in a random order.
  • Partition them into sets of 50.
  • Store all the partitioned IDs in session
  • Use your own paginator to know if you are on page=1 (set 1) or page=2 (set 2)
  • Once you have the correct set of 50 IDs, run a query whereIn the set and return to view
  • You will need to write your own paginator for the view.

Simple

  • add an order column to your Gallery
  • run a scheduled task at intervals (hourly or daily) which randomly changes the order value.
  • use standard pagination with the records all sorted by the order column (note, within a given period, all users will see the same 'random' order)

Both solutions really assume that you don't have thousands of records, and more like several hundred.

1 like

Please or to participate in this conversation.