mosamy / cacheable
Laravel package for caching models
Requires
- php: >=8.1
README
A lightweight Laravel package that adds powerful caching capabilities to your Eloquent models. Cache entire model collections with automatic invalidation and built-in search functionality.
Features
- 🚀 Simple trait-based caching for Eloquent models
- 🔄 Automatic cache invalidation on model save/delete
- 🔍 Built-in search functionality for cached collections
- 🎯 Custom cache queries with relationships support
- ⚙️ Configurable cache prefixes per model
- 🔗 Helper functions for quick access
- 💾 Works with any Laravel cache driver
Requirements
- PHP >= 8.1
- Laravel 8.0 or higher
Installation
composer require mosamy/cacheable
The package is auto-discovered by Laravel and will be automatically registered.
Quick Start
Basic Setup
Add the Cacheable trait to your Eloquent model:
use Illuminate\Database\Eloquent\Model;
use Mosamy\Cacheable\Cacheable;
class Post extends Model
{
use Cacheable;
}
Usage
// Fetch from database (standard query)
$posts = Post::get();
// Fetch from cache (or populate cache if empty)
$posts = Post::getCached();
// Using the helper function
$posts = getCached('post');
Advanced Features
Searching Cached Results
Search within cached collections with custom attributes:
// Search with explicit attributes
$results = Post::getCached()->searchCached('laravel', ['title', 'description']);
// Define searchable attributes on the model
class Post extends Model
{
use Cacheable;
public static function searchableAttributes()
{
return ['title', 'description', 'content'];
}
}
// Search using model defaults
$results = Post::getCached()->searchCached('laravel');
Custom Cache Queries
Override the cache() method to customize what gets cached (e.g., include relationships):
class Post extends Model
{
use Cacheable;
public static function cache()
{
return self::with('author', 'category')->get();
}
}
Cache Prefixes
Customize the cache key prefix per model. The cache key format is: {prefix}_{connection}_{table}
class Post extends Model
{
use Cacheable;
public static function cache_prefix()
{
return 'posts_';
}
}
// Cache key will be: "posts_mysql_posts"
By default, no prefix is used, so the cache key would be: mysql_posts
Automatic Cache Invalidation
Cache is automatically refreshed when a model is saved or deleted:
$post = Post::find(1);
$post->title = 'New Title';
$post->save(); // Cache is automatically refreshed
$post->delete(); // Cache is automatically cleared
Cache Management
Refresh Cache for a Model
Post::recache();
Clear Cache for a Model
Post::deleteCached();
Clear All Application Cache
php artisan cache:clear
Practical Example
// app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Mosamy\Cacheable\Cacheable;
class Post extends Model
{
use Cacheable;
public static function cache_prefix()
{
return 'blog_';
}
public static function searchableAttributes()
{
return ['title', 'slug', 'description'];
}
public static function cache()
{
return self::with('author', 'tags')
->where('published', true)
->get();
}
}
// Usage
$posts = Post::getCached();
$featured = $posts->searchCached('featured');
How It Works
- First Call: When
getCached()is called, it checks the cache. If not found, it executes the cache query and stores the result permanently. - Subsequent Calls: The cached data is returned immediately without database queries.
- Updates: When a model is saved or deleted, the cache is automatically invalidated and refreshed.
- Search: The
searchCached()macro filters the cached collection using the specified attributes.
Cache Drivers
This package works with any Laravel cache driver (file, array, redis, memcached, database). Configure your preferred driver in config/cache.php.
Helper Function Notes
The getCached('post') helper converts the model name to App\Models\Post. Ensure your models follow this naming convention or use Model::getCached() directly.
// These are equivalent (assuming Post model exists)
Post::getCached();
getCached('post'); // Resolves to App\Models\Post
License
This package is open-sourced software licensed under the MIT license.
Author
Created by Mohamed Samy