mosamy/cacheable

Laravel package for caching models

1.0.2 2023-03-26 22:04 UTC

This package is auto-updated.

Last update: 2025-04-27 06:28:09 UTC


README

Laravel eloquent model cache

Installation

composer require mosamy/cacheable

Usage


class Posts extends Model
{
  use \Mosamy\Cacheable\Cacheable;
}

// this will get records from database.
$posts = Posts::get();

// this will get records from cache.
$posts = Posts::getCached();

//in shortcut
$posts = getCached('posts');

To search in cache result you may use this code

$posts = Posts::getCached()->searchCached('keyword', ['name', 'description']);

To set the default cache search attributes use this function:


class Posts extends Model
{
  use \Mosamy\Cacheable\Cacheable;

  public static function searchableAttributes(){
    return ['name', 'description'];
  }

}

$posts = Posts::getCached()->searchCached('keyword');

If you need to cache model with a relation or custom query you should override this function


class Posts extends Model
{
  use \Mosamy\Cacheable\Cacheable;

  public static function cache(){
    return self::with('category')->get();
  }

}

By default, Cache name format is: prefix(connection name)(table name) . By default there is no prefix for the cache name. If you want to set a cache prefix you should override this method.


class Posts extends Model
{
  use \Mosamy\Cacheable\Cacheable;

  public static function cache_prefix(){
    return 'cache_';
  }

}

So the default name will be like "cache_mysql_posts"

To delete cache you can use this method:

Post::deleteCache();

or simply clear all cache

php artisan cachhe:clear