0

This is how am presently caching queries and i think it difficult to use model events to update cache when data change in tables after update because i need to update multiple caches.

<?php namespace App\Repositories; use App\Models\Book; //my model use \Cache; class BookEloquentRepository implements BookRepositoryInterface{ protected $cache_enabled = true; protected $cache_key = "book"; public function __construct(Book $book){ $this->book = $book; } public function find($id) { $this->cache_key = $this->cache_key ."_find_{$id}"; if( $this->cache_enabled && Cache::has($this->cache_key) ) return Cache::get($this->cache_key); $books = $this->book->find($id); Cache::forever($this->cache_key, $books); return $books; } public function all() { $this->cache_key = $this->cache_key ."_all"; if( $this->cache_enabled && Cache::has($this->cache_key) ) return Cache::get($this->cache_key); $books = $this->book->all(); Cache::forever($this->cache_key, $books); return $books; } public function allPublished() { $this->cache_key = $this->cache_key ."_allPublished"; if( $this->cache_enabled && Cache::has($this->cache_key) ) return Cache::get($this->cache_key); $books = $this->book->where('published', 1); Cache::forever($this->cache_key, $books); return $books; } } 

Is this the right way to do this? The challenge i have with these is how to update caches when record changes

I want to know if its possible to maintain only one cache for all records and be able to do stuffs like this without hitting the database.

 $books = Cache::get('books'); $book = $books->find(1); $published = $books->where('published', 1)->get(); 

This way i can only update only once cache 'books' when record changes after table update using model events

1 Answer 1

1
$published = Cache::remember('published', $minutes, function() { return Book::where('published', 1)->get(); }); 
Sign up to request clarification or add additional context in comments.

2 Comments

this will only work for published posts right? Following your example if i do same for all() and find() then i need to update 3 different caches when I update book table right? Am looking for a way to keep only one cache for books table
You can use Cache::flush(); after updating books table.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.