skip to Main Content

When I cache json string like so cache()->rememberForever('globals', fn() => json_encode(['foo' => 'bar']));.

The value stored in cache is actually "s:13:"{"foo":"bar"}";" rather than "{"foo":"bar"}"?

Is there a way I can store string without php serialisation?

2

Answers


  1. You should be able to store the string using the Cache::forever function. From Laravel docs Storing Items Forever:

    The forever method may be used to store an item in the cache permanently. Since these items will not expire, they must be manually removed from the cache using the forget method:

    Cache::forever(‘key’, ‘value’);

    Given that, I would change your code to something like the following:

    cache()->forever('globals', json_encode(['foo' => 'bar']));
    
    Login or Signup to reply.
  2. You would need to use the true cache storage like Redis::put(…). The cache facade(s) have a pretty helpful way of getting complex data in and out of cache. For instance you can cache models or associative arrays thru that facade and not worry about how it gets stringified behind the scenes. However, if you don’t want that kind of helper/handling to cache and restore your variables – then use the caching storage directly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search