How can I clear the cache in laravel using command line?
Instead of using CACHE_PREFIX you can use different redis databases. For ex: production => 1, staging => 2, development => 3. Use this links if you want to be a little bit more familiar with it:
So, in your .env file for each environment (production/stage/dev) you need to define different REDIS_CACHE_DB env value.
Link to the line uses this variable https://github.com/laravel/laravel/blob/2a2522d8824c0852e30a7e3e07d46a543eb4b33d/config/database.php#L142 . Examples of .env:
.env.production
REDIS_CACHE_DB=1
.env.stage
REDIS_CACHE_DB=2
.env.development
REDIS_CACHE_DB=3
Don't forget to clear config cache after changing env variables: https://laravel.com/docs/7.x/configuration#configuration-caching
Hope this helps!
Jaylen
Updated on April 06, 2020Comments
-
Jaylen about 4 years
I am using
Redis
to cache queries/routes in Laravel 5.2.I have 3 environments running on the same web server i.e "production", "staging", and "development."
For each environment I set a different cache
prefix
value to allow me to link the cache to different environment.In the
config/cache.php
file I changed the line'prefix' => 'laravel',
To
'prefix' => ENV('CACHE_PREFIX', 'laravel'),
Then in my
.env
file, I added the prefix for each environment like thisFor Dev
CACHE_PREFIX="LaravelDev"
For Staging
CACHE_PREFIX="LaravelStaging"
For Production
CACHE_PREFIX="LaravelProduction"
I know I can clear the cache from the command line like this
php artisan cache:clear
But the code above will clear the cache for all of my environments.
I only want to clear the cache for "LaravelDev" only and leave alone "LaravelStaging" and "LaravelProduction"
How can I clear the cache for a specific environment?
-
Jaylen almost 8 yearsWhen I execute the php artisan cache:clear it erases everything in Redis. I just tested it again. The problem that I am seeing is that the users that are using the app will get Mismatch token error because the session gets cleared too.
-
Chris Cynarski almost 8 yearsThe solution is to use different storage type for sessions in your Staging and Dev environments, so clearing the cache won't affect live users.
-
Jaylen almost 8 yearsCan't I create a command line that will execute the following code? $redis = Cache::getRedis(); $keys = $redis->keys(Cache::getPrefix() . "*"); foreach($keys as $key) { Cache::forget($key); }
-
Chris Cynarski almost 8 yearsSure, that should work as long as you don't have thousands of keys in your cache which could cause it to exceed available memory. Talking directly to Redis you could use SCAN / MATCH / COUNT command combination.