Javier Núñez
Javier Núñez

Reputation: 622

How do I check if a Cache element has expired in Laravel 5?

I want to store an array in Cache. I'm using "MemCached" as Cache driver and it works like a charm in queries, but I want to use it for my search suggestions. I've been looking at Laravel Documentation (http://laravel.com/docs/5.1/cache) but I haven't been able to find what I were looking for.

For example, I have this function in which if I find the element on Cache I get it. If not, I get results from DB and then store them on Cache for 10 minutes:

public function get_suggestions() {

      if(Cache::get('search_suggestions')) {
        return $search_suggestions;
      } else {
        $search_suggestions = Suggestions::get();
        Cache::put('search_suggestions', '$search_suggestions', 10);
        return $search_suggestions;          
}

}

Some questions:

  1. If the element in Cache expires, what will the Cache::get function returns?
  2. There is a function to check if the element exists in the database but is there anyone to check if the Cache item has expires?
  3. Is my approach OK to manage the Cache?

Upvotes: 0

Views: 4242

Answers (1)

Philipp
Philipp

Reputation: 15629

You could use Cache::has to check for existance.

But in your case I suggest to use Cache::remember

public function get_suggestions() {
    return Cache::remember('search_suggestions', 10, function() {
        return Suggestions::get();
    });
}

Upvotes: 1

Related Questions