dark
dark

Reputation: 405

Saving an array of data to cache

My understanding of cache might be blurry. But i am trying to save an array of record ids to cache and get them. I know the normal way of putting data in cache is

$expiresAt = now()->addMinutes(10);

Cache::put('key', 'value', $expiresAt);

and then to get is

Cache::get('key');

With each record i save to the cache, when i do dd(Cache::get('key')); i only get the last saved record. how can i save and get an array of data with cache ?

Upvotes: 0

Views: 546

Answers (2)

HieuMinh
HieuMinh

Reputation: 41

Just simply put to value an array then next time you get it from cache, it will be an array.

Upvotes: 0

daremachine
daremachine

Reputation: 2788

Cache value is saved under specific key. If you put multiple values into Cache with same key then only last value will be saved and retrived.

You can use it like below

$articles = [...];

foreach($articles as $article)
{
    $expiresAt = now()->addMinutes(10);

    Cache::put('key_' . $article.ID, 'value', $expiresAt);
}

and later use

Cache::get('key_' . $article.ID);

Upvotes: 1

Related Questions