eriktobben's avatar

Cache::remember - forever?

Hi,

I have some settings stored in the database and I want to cache them forever as they don't change often. When the user updates his settings, I delete the cache and add the new version to the cache.

How can I set this method to store the data forever?

´´´ $value = Cache::remember('users', $minutes, function () { return DB::table('users')->get(); }); ´´´

0 likes
6 replies
eriktobben's avatar

But how can I use this with a closure so that Laravel performs a query if the key don't exists in the cache?

Cronix's avatar

Just check if the key exists. If not, cache it then return the cached value.

if ( ! Cache::get(key)) {
  $query = Model::find(blah);
  Cache::forever(key, $query);
}

return Cache::get(key);

There are other ways as well. Here's a good video: https://laracasts.com/lessons/caching-essentials

1 like
d3xt3r's avatar

I remember there used to be a caching strategy for query builder. Is it no longer the case ?

martinbean's avatar
Level 80

@eriktobben You’re looking for the rememberForever() method:

Cache::rememberForever('cache_key', function () {
    // The result of the closure will be cached
    // until you manually clear the cache key.
    return $something;
});
1 like

Please or to participate in this conversation.