PHP code example of ymigval / laravel-model-cache

1. Go to this page and download the library: Download ymigval/laravel-model-cache 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/ */

    

ymigval / laravel-model-cache example snippets


  'providers' => [
      // Other service providers...
      YMigVal\LaravelModelCache\ModelCacheServiceProvider::class,
  ],



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use YMigVal\LaravelModelCache\HasCachedQueries;

class Post extends Model
{
    use HasCachedQueries;
    
    // Optional: Override the default cache duration for this model
    protected $cacheMinutes = 120; // 2 hours
    
    // Optional: Override the global prefix from config('model-cache.cache_key_prefix') for this model
    protected $cachePrefix = 'posts_';
}

// This automatically uses the cache with default duration
$posts = Post::where('published', true)->get();

// This also uses the cache with default duration
$post = Post::where('id', 1)->first();

// Add custom cache duration
$posts = Post::where('status', 'active')->remember(60)->get();

// Explicitly get results from cache (or store in cache if not present)
$posts = Post::where('published', true)->getFromCache();

// Explicitly get first result from cache
$post = Post::where('id', 1)->firstFromCache();

// Set custom cache duration for a specific query
$posts = Post::where('status', 'active')->remember(30)->getFromCache();

// In your model
public function scopePopular($query)
{
    return $query->where('views', '>', 1000)
                ->orderBy('views', 'desc')
                ->remember(60); // Cache popular posts for 1 hour
}

// In your controller - both work the same
$posts = Post::popular()->get(); // Implicit
$posts = Post::popular()->getFromCache(); // Explicit

$minutes = $user->isAdmin() ? 5 : 60; // Less cache time for admins who need fresh data
$posts = Post::latest()->remember($minutes)->get();

// Cache the posts but load comments fresh every time
$posts = Post::with(['comments' => function($query) {
    $query->withoutCache(); // Skip cache for this relation
}])->remember(30)->get();



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use YMigVal\LaravelModelCache\HasCachedQueries;
use YMigVal\LaravelModelCache\ModelRelationships;

class Post extends Model
{
    use HasCachedQueries, ModelRelationships;
    
    // Your relationship methods...
    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }
}

// Sync a belongsToMany relationship and flush cache
$post->syncRelationshipAndFlushCache('tags', [1, 2, 3]);

// Attach records to a belongsToMany relationship and flush cache
$post->attachRelationshipAndFlushCache('tags', [4, 5], ['added_by' => 'admin']);

// Detach records from a belongsToMany relationship and flush cache
$post->detachRelationshipAndFlushCache('tags', [1, 3]);

// These operations will automatically flush the cache
$post->tags()->attach(1);
$post->tags()->detach([2, 3]);
$post->tags()->sync([1, 4, 5]);
$post->tags()->updateExistingPivot(1, ['featured' => true]);

   // Add this in your controller
   if (Cache::has($cacheKey)) {
       Log::info('Cache hit for key: ' . $cacheKey);
   } else {
       Log::info('Cache miss for key: ' . $cacheKey);
   }
   

$freshData = YourModel::withoutCache()->get();

// Old approach with manual caching
$cacheKey = 'posts_' . md5($query);
$posts = Cache::remember($cacheKey, 60, function() use ($query) {
    return Post::where(...)->get();
});

// New approach with this package
$posts = Post::where(...)->remember(60)->get();
shell script
php artisan vendor:publish --provider="YMigVal\LaravelModelCache\ModelCacheServiceProvider" --tag="config"
 
     php artisan cache:table
     php artisan migrate
 php
// config/model-cache.php
'cache_store' => env('MODEL_CACHE_STORE', 'redis'),
 shell
php artisan mcache:flush {model?}
 shell
# Clear cache for User model
php artisan mcache:flush "App\Models\User"

# Clear cache for Product model
php artisan mcache:flush "App\Models\Product"
 shell
php artisan mcache:flush