This package provides a set of macros to cache your Laravel Queries just like Cache::remember.
$featuredPost = Post::published()->orderByMostViews()
->cacheDay('post:featured') // <- Here
->first();
You can install the package via composer:
composer require juampi92/laravel-query-cache
That's it! No config or Trait necessary. The package auto-discovery will boot the macros.
Instead of doing:
Cache::remember('post:count', $ttl, () => Post::published()->count());
You now do:
Post::published()->cache('post:count', $ttl)->count();
You can use it in Eloquent Queries as well as in normal Queries.
DB::table('posts')
->whereNotNull('published_at')
->latest()
->cacheHour('post:latest')
->first();
Posts::published()
->cacheHour('post:count')
->count();
List of macros:
Post::cache('cache:key', $ttl)->get();
Post::cacheMinute('cache:key')->first();
Post::cacheHour('cache:key')->pluck('id');
Post::cacheDay("cache:key:$id")->find($id);
Post::cacheWeek('cache:key:paginate:10')->paginate(10);
Post::cacheForever('cache:key')->count();
Post::query()
->where(...)
->cache('post:count')->store('redis')
->count();
This is maybe more advanced, but you can do so by opting out of discovery, and then importing it yourself:
use Juampi92\LaravelQueryCache\LaravelQueryCacheServiceProvider as BaseServiceProvider;
class LaravelQueryCacheServiceProvider extends BaseServiceProvider
{
protected function getCustomTimes(): array
{
return array_merge(
parent::getCustomTimes(),
[
'rememberForever' => null,
'cacheFifteenMinutes' => 60 * 15,
]
);
}
}
The original method has
[
'cacheForever' => null,
'cacheMinute' => 60,
'cacheHour' => 60 * 60,
'cacheDay' => 60 * 60 * 24,
'cacheWeek' => 60 * 60 * 24 * 7,
]
This package is supposed to be a nice integration of Cache remember inside the Query Builder. If you're looking for a advanced eloquent specific cache, I recommend to check out laravel-eloquent-query-cache.
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.