juampi92 / laravel-query-cache
Provide easy interface for caching laravel queries
Fund package maintenance!
Juampi92
Installs: 15 451
Dependents: 0
Suggesters: 0
Security: 0
Stars: 25
Watchers: 2
Forks: 3
Open Issues: 0
Requires
- php: >=7.4
- illuminate/cache: ^8.0|^9.0|^10.0
- illuminate/database: ^8.0|^9.0|^10.0
- illuminate/support: ^8.0|^9.0|^10.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.8
- mockery/mockery: ^1.4.2
- orchestra/testbench: ^v7.0
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.3
This package is auto-updated.
Last update: 2024-11-12 19:56:44 UTC
README
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();
Installation
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.
Usage
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();
Advanced usage
Different store
Post::query() ->where(...) ->cache('post:count')->store('redis') ->count();
Add your custom cache duration
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, ]
Disclaimer
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.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.