title: Laravel Repository caching and pagination
body: <p>I have created a base repository and am now extending it to add caching, but the problem I seem to be experiencing more than most is <code>pagination</code></p>
  
  <p>in my <code>all()</code> method, I do the following without caching:</p>
  
  <pre><code>public function all($pagination = 20)
  {
      try
      {
          $query = $this-&gt;model-&gt;newQuery();
          return $this-&gt;handlePagination($query, $pagination);
      }
      catch (Exception $e)
      {
          throw $e;
      }
  }
  
  protected function handlePagination($query, $pagination)
  {
      if (is_null($pagination))
      {
          return $query;
      }
      $collection = $query-&gt;paginate($pagination);
      return $collection;
  }
  </code></pre>
  
  <p>This is working well, but when I try to implement caching, I want to cache each model individually and store the keys for each collection, so, if I was paginating all of the entries, I would store each paginated collection in a cache:</p>
  
  <pre><code>cache set.1 [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
  cache set.2 [21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]
  </code></pre>
  
  <p>etc...</p>
  
  <p>the problem is that is seems impossible to use the actual pagination class to return the results since you are paginating only the <code>id</code></p>
  
  <p>I could return the data and the paginator separately but that seems very hacky.</p>
  
  <p>Is there a way to repopulate the <code>Paginator</code> class with model data without over-writing the whole thing?</p>
  
  <p>EDIT</p>
  
  <p>I was thinking about something like this:</p>
  
  <pre><code>public function all($pagination = 20)
  {
      try
      {
          $cache_key = $this-&gt;cache_key . '.all';
          $ids = Cache::get($cache_key);
          if (! $ids)
          {
              $query = $this-&gt;model-&gt;newQuery();
              $ids = $query-&gt;pluck('id');
              Cache::put($cache_key, $ids, $this-&gt;cache_ttl);
          }
  
          $ids = $this-&gt;handlePagination($ids, $pagination);
          $collection = new Collection();
          foreach ($ids as $id)
          {
              if ($model = $this-&gt;find($id))
              {
                  $collection-&gt;put($id, $model);
              }
          }
          return $collection;
      }
      catch (Exception $e)
      {
          throw $e;
      }
  }
  
  /**
   * @var \Illuminate\Pagination\Paginator
   */
  protected $paginator;
  public function handlePagination($array, $pagination = 20)
  {
      if (!is_null($pagination))
      {
          $this-&gt;paginator = Paginator::make($array, count($array), $pagination);
          return $this-&gt;paginator-&gt;getItems();
      }
      return $array;
  }
  
  public function getPaginator()
  {
      return $this-&gt;paginator;
  }
  </code></pre>