Laravel cache does not store null value

Viewed 5325

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.

2 Answers

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