Andrius Solopovas
Andrius Solopovas

Reputation: 1057

How can I store raw json string in redis cache using laravel without php serialization?

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?

Upvotes: 0

Views: 2784

Answers (2)

Tarek Adam
Tarek Adam

Reputation: 3525

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.

Upvotes: 1

Zacx
Zacx

Reputation: 438

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']));

Upvotes: 0

Related Questions