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.

upvote
  flag
What's the error? – Alfa

2 Answers 11

up vote 3 down vote accepted

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())

Starting with Laravel 5.4 the method Cache::has() will return false if the value is null or false, not just for null as for previous versions. To overcome this problem for version 5.4, but also for older versions with null value, we can store the result into an array like this: Cache::put(['data' => $variable]) where $variable can be null, false or any value.

\Cache::put('key', ['data' => null], 5);
var_dump(\Cache::has('key')); //prints true
var_dump(\Cache::get('key')); //prints array (size=1) 'data' => null

\Cache::put('key2', ['data' => false], 5);
var_dump(\Cache::has('key2')); //prints true
var_dump(\Cache::get('key2')); //prints array (size=1) 'data' => boolean false

\Cache::put('key3', ['data' => 'ok'], 5);
var_dump(\Cache::has('key3')); //prints true
var_dump(\Cache::get('key3')); //prints array (size=1) 'data' => string 'ok' (length=6)

Not the answer you're looking for? Browse other questions tagged or ask your own question.