Laravel Cache Forget Remember Forever Cache Not Working?

2.4k Views Asked by At

I am trying to store the last run time of a scheduled job in Laravel. However, the cache is not updating the date. I want the cache to be remembered until the function is called again.

public function setLastRun() {
   Cache::forget('last_automation_api_run');
   Cache::rememberForever('last_automation_api_run', function () {
          return now()->toDateTimeString();
   });
}
2

There are 2 best solutions below

1
parth On

You should use remember and forget method in different functions.

public function getLastRun() {
   return \Cache::rememberForever('last_automation_api_run', function () {
          return now()->toDateTimeString();
   });
}

public function forgetLastRun() {
   \Cache::forget('last_automation_api_run');
}

Every time you delete the cache before fetching cache values makes, logically incorrect.

And you have to return the values coming from rememberForever cache method.

0
apokryfos On

If you're using a clustered cache then there's a chance the first change hasn't propagated through the cache when you make the 2nd one. If that is the case (or generally for what you're doing) you can try the following:

public function setLastRun() {
   Cache::put('last_automation_api_run', now()->toDateTimeString());
}

this should mindlessly overwrite the current value rather than deleting and readding it.