Archive for October, 2025


Laravel default to file cache when redis is down

Create this file in app/Cache/CustomCacheManager.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
namespace App\Cache;
 
use Illuminate\Cache\CacheManager;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Arr;
 
class CustomCacheManager extends CacheManager
{
    /**
     * Create an instance of the Redis cache driver.
     *
     * @param  array  $config
     * @return \Illuminate\Cache\Repository
     */
    protected function createRedisDriver(array $config) {
        $isReady = true;
        try {
            $connection = Arr::get($config, 'connection', 'default') ?: 'default';
            $redis = Redis::connection($connection);
        } catch (\Exception $e) {
            $isReady = false;
        }
        if($isReady) {
            return parent::createRedisDriver($config);
        } else {
            \Log::warning('Redis connection failed, falling back to file cache: ' . $e->getMessage());
            return parent::createFileDriver(\Config::get('cache.stores.file'));
        }
    }
}

Create this provider for it in app/Providers/CustomCacheServiceProvider.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace App\Providers;
 
use App\Cache\CustomCacheManager;
use Illuminate\Cache\CacheServiceProvider;
 
class CustomCacheServiceProvider extends CacheServiceProvider
{
    public function register()
    {
        $this->app->singleton('cache', function ($app) {
            return new CustomCacheManager($app);
        });
        $this->app->singleton('cache.store', function ($app) {
            return $app['cache']->driver();
        });
    }
}

and add it to config/app.php before the AppServiceProvider

1
2
App\Providers\CustomCacheServiceProvider::class,
App\Providers\AppServiceProvider::class,

Permalink » No comments