1

I want to remove all the cache items whose key is starting with custom string.

Currently, I have a PermissionObserver for the Permission model with a custom trait ObserverEvent to called this handle method.

class PermissionObserver
{
    use ObserverEvent;

    private function handle(Permission $permission)
    {
        $emails = User::pluck('email');
        foreach ($emails as $email) {
            $key  = 'permission_index_'. $email;
           if (cache()->has($key)) {
                cache()->forget($key);
           }
        }

        $ids = User::pluck('id');
        foreach ($ids as $id) {
            $key1  = 'permission_create_users_'. $id;
            $key2  = 'permission_edit__users_'. $id;
            if (cache()->has($key1)) {
                 cache()->forget($key1);
            }
            if (cache()->has($key2)) {
                cache()->forget($key2);
            }
        }

        // It will continue like this....

        logger()->build(CUSTOM_BUILD_LOG_CHANNEL)->info("PERMISSION_CACHE_CLEARED");
    }
}

Now it's getting bigger and performance issues. Also, I have this type of logic for all models.

Update

I am not using any redis, database, dynamodb, memcached or octane driver for the cache store. I am using default storage i.e. file so provide the solution accordingly.

Is there a way to clear all the cache with starting with string permission so that I can do like this.

cache()->forget('permission*') // this doesn't work
JS TECH
  • 1,556
  • 2
  • 11
  • 27
  • Since you are using a file cache you can remove all the `cache()->has` calls because by default the file cache won't delete an entry unless it exists and will return falls if it doesn't delete it (rather than failing the call) so you might get "some" speed back. – apokryfos Sep 19 '22 at 05:26
  • possible duplicate https://stackoverflow.com/questions/35074418/laravel-erase-all-cache-redis-keys-that-contain-a-specific-string – Haseeb Zulfiqar Sep 19 '22 at 06:43
  • Does this answer your question? [Laravel - Erase all cache / redis keys that contain a specific string](https://stackoverflow.com/questions/35074418/laravel-erase-all-cache-redis-keys-that-contain-a-specific-string) – Haseeb Zulfiqar Sep 19 '22 at 06:44

0 Answers0