Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel cache does not store null value

I'm using Laravel 5.2 and wants to cache eloquent results, but it does not store empty results (= null) on cache. Is there any way to do it?

return Cache::remember("cacheKey_{$id}", 120, function () use ($id) {
  return FooModel::where(...)->first();
});

When the result is not empty, the cache is working properly.

like image 742
rhythm Avatar asked Sep 01 '25 04:09

rhythm


1 Answers

Laravel cache doesn't allow to store null values in cache but you can store false values.

    cache(['key' => null],120)
    var_dump(Cache::has('key')); //prints false
    cache(['key' => false],120)
    var_dump(Cache::has('key')); //prints true

So I would suggest you to try something like:

return Cache::remember("cacheKey_{$id}", 120, function () use ($id) {
  $your_check = FooModel::where(...)->first();
  return is_null($your_check) ? false : $your_check;
});

Alternatively you can assume that when there isn't the key, it would be null (check with Cache::has() or isset())

like image 95
aaron0207 Avatar answered Sep 03 '25 08:09

aaron0207