miradnan/laravel-model-caching
composer require miradnan/laravel-model-caching and publish the config (if needed) with php artisan vendor:publish --provider="miradnan\QueryCache\QueryCacheServiceProvider".use miradnan\QueryCache\Traits\QueryCacheable; to your model and set $cacheFor (in seconds) to enable caching for all queries on that model.
class Post extends Model {
use QueryCacheable;
public $cacheFor = 3600; // Cache for 1 hour
}
$posts = Post::where('published', true)->get();
Verify cache hits by checking Laravel’s cache driver logs or using Cache::getStore()->get($cacheKey).SELECT * FROM posts WHERE published = 1).App\Models\Post).where, orderBy, limit).model:App\Models\Post:sql:SELECT * FROM posts WHERE published = 1.$cacheFor TTL.TableCacheable trait for caching entire tables (e.g., Country::all()).
class Country extends Model {
use TableCacheable;
public $cacheFor = 86400; // Cache for 24 hours
}
Post::clearCache(); // Clears all cached queries for Post.
Post::clearCacheForQuery('SELECT * FROM posts WHERE published = 1'); // Clears specific query.
shouldCache():
public function shouldCache() {
return !request()->has('nocache');
}
config/query-cache.php (e.g., redis, database)..env:
DB_LOG_QUERIES=true
Check logs to verify cached vs. uncached queries.where('id', 1) vs. find(1)) may generate different keys but cache the same data.getCacheKey() in your model:
protected function getCacheKey() {
return 'normalized:key:' . md5($this->getTable() . serialize($this->getQuery()->getQuery()));
}
$cacheFor too high can stale data. Too low increases DB load.public $cacheFor = env('POST_CACHE_TTL', 3600);
with() may not cache relationships correctly.load() after fetching cached data.TableCacheable) loads entire tables into memory.protected function logCacheEvent($event) {
\Log::debug("QueryCache [{$event}]: " . $this->getCacheKey());
}
\Log::debug('Cache Key:', [
'key' => Post::query()->where('published', true)->getCacheKey()
]);
use Illuminate\Support\Facades\Cache;
protected function getCacheTags() {
return ['posts:published'];
}
Cache::tags(['posts:published'])->flush().getCachedQuery() to modify cached queries (e.g., add select clauses):
protected function getCachedQuery() {
return parent::getCachedQuery()->select(['id', 'title']);
}
handleCacheMiss() to run custom logic when cache misses:
protected function handleCacheMiss() {
// Custom logic (e.g., analytics, fallback data)
return $this->newQuery()->get();
}
$cacheFor is null, caching is disabled.file, redis) is available in config/cache.php..env to disable caching globally:
QUERY_CACHE_ENABLED=false
How can I help you explore Laravel packages today?