scopedStoreNames(); foreach ($stores as $storeName) { $this->originalConnections[$storeName] = $this->config->get("cache.stores.{$storeName}.connection") ?? config('tenancy.database.central_connection'); $this->originalLockConnections[$storeName] = $this->config->get("cache.stores.{$storeName}.lock_connection") ?? config('tenancy.database.central_connection'); $this->config->set("cache.stores.{$storeName}.connection", 'tenant'); $this->config->set("cache.stores.{$storeName}.lock_connection", 'tenant'); /** @var DatabaseStore $store */ $store = $this->cache->store($storeName)->getStore(); $store->setConnection(DB::connection('tenant')); $store->setLockConnection(DB::connection('tenant')); } if (static::$adjustGlobalCacheManager) { // Preferably we'd try to respect the original value of this static property -- store it in a variable, // pull it into the closure, and execute it there. But such a naive approach would lead to existing callbacks // *from here* being executed repeatedly in a loop on reinitialization. For that reason we do not do that // (this is our only use of $adjustCacheManagerUsing anyway) but ideally at some point we'd have a better solution. $originalConnections = array_combine($stores, array_map(fn (string $storeName) => [ 'connection' => $this->originalConnections[$storeName], 'lockConnection' => $this->originalLockConnections[$storeName], ], $stores)); TenancyServiceProvider::$adjustCacheManagerUsing = static function (CacheManager $manager) use ($originalConnections) { foreach ($originalConnections as $storeName => $connections) { /** @var DatabaseStore $store */ $store = $manager->store($storeName)->getStore(); $store->setConnection(DB::connection($connections['connection'])); $store->setLockConnection(DB::connection($connections['lockConnection'])); } }; } } public function revert(): void { foreach ($this->originalConnections as $storeName => $originalConnection) { $this->config->set("cache.stores.{$storeName}.connection", $originalConnection); $this->config->set("cache.stores.{$storeName}.lock_connection", $this->originalLockConnections[$storeName]); /** @var DatabaseStore $store */ $store = $this->cache->store($storeName)->getStore(); $store->setConnection(DB::connection($this->originalConnections[$storeName])); $store->setLockConnection(DB::connection($this->originalLockConnections[$storeName])); } TenancyServiceProvider::$adjustCacheManagerUsing = null; } protected function scopedStoreNames(): array { return array_filter( static::$stores ?? array_keys($this->config->get('cache.stores', [])), function ($storeName) { $store = $this->config->get("cache.stores.{$storeName}"); if (! $store) return false; if (! isset($store['driver'])) return false; return $store['driver'] === 'database'; } ); } }