Skip to content

Commit 570a8d4

Browse files
committed
Add pagination caching
1 parent 3f5ea91 commit 570a8d4

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/CachedBuilder.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,24 @@ public function min($column)
125125
return $this->cachedValue($arguments, $cacheKey, $method);
126126
}
127127

128+
public function paginate(
129+
$perPage = null,
130+
$columns = ['*'],
131+
$pageName = 'page',
132+
$page = null
133+
) {
134+
if (! $this->isCachable) {
135+
return parent::paginate($perPage, $columns, $pageName, $page);
136+
}
137+
138+
$arguments = func_get_args();
139+
$page = $page ?: 1;
140+
$cacheKey = $this->makeCacheKey($columns, null, "-paginate_by_{$perPage}_{$pageName}_{$page}");
141+
$method = 'paginate';
142+
143+
return $this->cachedValue($arguments, $cacheKey, $method);
144+
}
145+
128146
public function pluck($column, $key = null)
129147
{
130148
if (! $this->isCachable) {

tests/Unit/CachedBuilderTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -883,4 +883,24 @@ public function testFindOrFailCachesModels()
883883
$this->assertEquals($cachedResults->toArray(), $author->toArray());
884884
$this->assertEquals($liveResults->toArray(), $author->toArray());
885885
}
886+
887+
public function testPaginationIsCached()
888+
{
889+
$authors = (new Author)
890+
->paginate(3);
891+
892+
$key = sha1('genealabs:laravel-model-caching:genealabslaravelmodelcachingtestsfixturesauthor-paginate_by_3_page_1');
893+
$tags = [
894+
'genealabs:laravel-model-caching:genealabslaravelmodelcachingtestsfixturesauthor',
895+
];
896+
897+
$cachedResults = $this->cache()
898+
->tags($tags)
899+
->get($key)['value'];
900+
$liveResults = (new UncachedAuthor)
901+
->paginate(3);
902+
903+
$this->assertEquals($cachedResults->toArray(), $authors->toArray());
904+
$this->assertEquals($liveResults->toArray(), $authors->toArray());
905+
}
886906
}

0 commit comments

Comments
 (0)