Muzammil's avatar

L5 Cache with Pagination

Hi floks, i'm trying to implement cache db query with pagination , but it only shows first cached set of data no matter on which page you are. Below is what i have done so far:

$allProducts = Cache::remember('allProducts','30',function(){

            return Products::orderby('name','ASC')->paginate(15);
        });
        
        return view('manage-products',['products' => $allProducts]);

Anybody have come across this issue?? any help or suggestion would be much appreciated. Thank you :)

0 likes
2 replies
veve286's avatar
veve286
Best Answer
Level 8

$page=Request::input('page','1');

$allProducts = Cache::remember('allProducts_'.$page,'30',function(){

        return Products::orderby('name','ASC')->paginate(15);
    

});

return view('manage-products',['products' => $allProducts]);

You have to give a name for each page other wise Cache will only store first page of your pagination results. So for now if you go to

 
foo?page=2  // cache will store or reterive from allProducts_2
foo?page=3  // cache will store or reterive from allProducts_3

1 like

Please or to participate in this conversation.