Laravel: regenerate cache

60 Views Asked by At

I am using cache to store data structure from database:

Cache::forever(static::DATA_STRUCTURE, json_encode($tree));

However before I generate there should cleaned old:

Artisan::call('cache:clear');

But generating new cache takes some time and I want to store old cache until new will be generated.

I am using typical file cache. Does anyone can provide some hint? Maybe we can do it from the box or some package.

At this moment I see only one solution: just generate in some other folder and remove old folder with cache, then move new instead the old.

2

There are 2 best solutions below

0
Denissio Inkognito On BEST ANSWER

I solved my problem when I pushed data in variables, cleaned the cache by tag, then pushed new data to this tag.

0
dz0nika On

As Maksim said you can use Cache::put, but also you can set the temp values something like this

// Step 1: Store the new cache data in a temporary cache key
Cache::put(static::TEMP_DATA_STRUCTURE, json_encode($tree), now()->addMinutes(5));

try {
    // Step 2: If generation is successful, update the main cache key with the new data
    Cache::forever(static::DATA_STRUCTURE, $tree);
} catch (\Exception $e) {
    // Handle any errors that occur during cache update
    Log::error('Error updating cache: ' . $e->getMessage());

    // Optionally, rollback the temporary cache key
    Cache::forget(static::TEMP_DATA_STRUCTURE);
}