kkhicher1's avatar

Pagination + inRandomOrder duplicate Record Fetch

$page = \request()->input('page', 1);
        $images = Cache::remember('images-'.$page, 60*60, function (){
            return Image::inRandomOrder()->paginate(10);
        });

        return json_encode($images);

next page duplicated record fetch and cache in not problem. i tried before implementing cache system

0 likes
7 replies
Snapey's avatar

two problems

  1. every page number will return the same results until the cache expires

  2. in random order means that you can see the same item appear on page 2 since they are shuffled on every load

kkhicher1's avatar

but it can be randomize after cache expire

MichalOravec's avatar

Behind the scene Laravel use rand() function for inRandomOrder

https://github.com/laravel/framework/blob/8.x/src/Illuminate/Database/Query/Builder.php#L2013

https://github.com/laravel/framework/blob/8.x/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php#L101

And here is documentation for that rand function

https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_rand

When you pass some argument to that inRandomOrder function, the order will be still same on each page when you use pagination.

Please or to participate in this conversation.