kfirba's avatar
Level 50

Caching pagination with repository

Hello!

I have some repositories for my models and I would like to add a cache decorator to some of them. The only issue is that I have a method paginate() which I don't know how to cache:

 public function paginate($perPage = 15, $columns = ['*'])
    {
        return $this->model->paginate($perPage, $columns);
    }

How can I cache it efficiently and make it aware to the current requested page?

0 likes
8 replies
bimalshah72's avatar

Try this,

 public function paginate($perPage = 15, $columns = ['*'])
 {
    return $this->cache->rememberForever(class_basename($this->model).'_'.$perPage.'_'.implode(', ',$columns), function () {
           return $this->model->paginate($perPage, $columns);
    }
     
 }
bimalshah72's avatar

I am assuming you have already enabled cache and in repository used

use Illuminate\Contracts\Cache\Repository as Cache;

and

public function __construct(Cache $cache) {
    $this->cache = $cache;
}
kfirba's avatar
Level 50

@bimalshah72 hey. How does your code is aware to the requested page? If I have /collection?page=3 then obviously I want page number 3 results. I'm not sure the code you just shared is aware of that and I think it will always return the first page.

bimalshah72's avatar

True ..

What about if you append current page in rememberforever? i.e. model->currentPage() (if model is instanceOf LengthAwarePaginator)

kfirba's avatar
Level 50

@bimalshah72 well I'm not sure how would it work. In order to have a lengthAwarePaginator we need to create a paginatior which means we need to query the DB for the collection. The only solution I currently see is to have a Request object in the paginate method and check for a page in the query string and append that to the generated key. Will have to test that theory out :)

bimalshah72's avatar

Yes, that would work, - in short we need unique key to identify

kfirba's avatar
Level 50

@bimalshah72 I guess. When I will implement that in my application and test it I will post here a solution

Please or to participate in this conversation.