Easy Eloquent + Relation Cache Management

Submitted by nlogachev - 10 years ago

Combining Model Observers and Cache Tags for very simple but elegant automatic cache flushing on Eloquent Model updates. Can handle both a Model and its Relations easily!

////
/* Subclassable, generic Model Observer */
////

class ModelObserver {

    protected function clearCacheTags($tags)
	{
		Cache::tags($tags)->flush();
	}
	
	public function saved($model)
	{
		$this->clearCacheTags($model->getTable());
	}

	public function deleted($model)
	{
		$this->clearCacheTags($model->getTable());
	}

	public function restored($model)
	{
		$this->clearCacheTags($model->getTable());
	}

}

////
/* Base Model that other models subclass */
////

class BaseModel extends \Illuminate\Database\Eloquent\Model {
    
	public static function table()
	{
		$instance = new static;
		return $instance->getTable();
	}
    
}

////
/* Set up observers, for example in start/global.php */
////

$modelObserver = new ModelObserver;
Comment::observe($modelObserver);
Post::observe($modelObserver);
User::observe($modelObserver);

////
/* Putting it all together: note how regardless of which model type gets 
 * updated, we've tagged this Cache closure with each of the involved models'
 * tables, so we will automatically get a fresh result set in case of changes.
 */
////

$posts = Cache::tags(User::table(),Post::table(),Comment::table())->remember('whatever_unique_key_you_want', 60 * 24, function() {
    return Post::with('user','comments')
        ->latest()
        ->take(10)
		->get();
});