JS TECH
JS TECH

Reputation: 1583

Remove all items from cache whose key start with string

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

Upvotes: 3

Views: 1390

Answers (0)

Related Questions