0

The easiest way to get a entries sort by random is to apply this: .orderBy('RAND()').

This is very useful, however I have a case where I need to get entries (which are adverts) in a random sequence which should go forward at each reload or at least present a different equitable result at each reload.

Considering these entries: A, B, C. I could get this on first load (first random result): C, B, A. Then on first next reload (other random, but try to follow sequence to prevent duplicated display): A, C, B ← not C, B, A.

When finished all unique combinations possible, restart a random sequence.

What would be the best solution?

1 Answer 1

1

You can store the ID of entries you've already displayed to this user in the session, then use .id(['not', 1, 2]) to exclude those entries on later request. On each page load, add the randomly selected entry to the list of ads already displayed. When all ads have been shown, maybe clear the list and start anew.

However, this presents several problems. Every time randomness and state are involved, you severely limit your ability to cache effectively. If you cache a random result, it won't look so random any more, and if the output of a template depends on values in the session, you can't cache that output at all.

I would recommend building this in a way that allows the output to be cached. For example:

  • Query and output all ads with the [hidden] attribute, then use JavaScript to randomly toggle one of them.
  • Create a controller that returns data for a random ad, then fetch() and insert it using JavaScript in the frontend.

In both cases, you can use the same logic to exclude ads you've already shown. If you store the list in localStorage, you can even avoid repeated ads across browser sessions.

Of course, using JavaScript means the ad might display with a slight delay and might negatively impact your CLS score.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.