PHP code example of genealabs / laravel-model-caching
1. Go to this page and download the library: Download genealabs/laravel-model-caching library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
genealabs / laravel-model-caching example snippets
$posts = Cache::remember('posts:active:page:1', 3600, function () {
return Post::where('active', true)->with('comments')->paginate();
});
// And in every observer or event listener…
Cache::forget('posts:active:page:1');
// Hope you remembered every key variant! 😅
// Just query. Caching and invalidation happen automatically. ✨
$posts = Post::where('active', true)->with('comments')->paginate();
namespace App\Models;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Model;
abstract class BaseModel extends Model
{
use Cachable;
}
namespace App\Models;
use GeneaLabs\LaravelModelCaching\CachedModel;
class Post extends CachedModel
{
// ...
}
class Post extends BaseModel
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
}
// All cached automatically — the query, the eager loads, everything. 🪄
$posts = Post::with('comments', 'tags')
->where('published', true)
->latest()
->paginate(15);
namespace App\Models;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use Cachable;
protected $cachePrefix = 'tenant-123';
}
namespace App\Models;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use Cachable;
protected $cacheCooldownSeconds = 300; // 5 minutes ⏱️
}
// Activate using the model's default (300 seconds)
Comment::withCacheCooldownSeconds()->get();
// Or override with a specific duration
Comment::withCacheCooldownSeconds(30)->get();
use GeneaLabs\LaravelModelCaching\Facades\ModelCache;
// Single model
ModelCache::invalidate(App\Models\Post::class);
// Multiple models
ModelCache::invalidate([
App\Models\Post::class,
App\Models\Comment::class,
]);
namespace App\Models;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Model;
class ImportedProduct extends Model
{
use Cachable;
protected $cacheTtlSeconds = 3600; // 1 hour ⏱️
}
// routes/console.php
use Illuminate\Support\Facades\Schedule;
Schedule::command('cache:prune-stale-tags')->hourly();
// In your TestCase setUp() or phpunit.xml
config(['laravel-model-caching.enabled' => false]);