I’m using the stancl/tenancy
package in a Laravel v12 application and need to apply tenant-specific scoping to cached values. By default, the package overrides Laravel’s CacheManager
to apply tags()
based on the tenant ID.
However, this approach crashes when using cache drivers like database
that don’t support tagging, throwing:
BadMethodCallException: This cache store does not support tagging.
I tried overriding the CacheManager
using app()->extend('cache', ...)
in my service provider, but it gets initialized before tenancy is bootstrapped, making tenant()
return null
, which leads to:
Call to a member function getTenantKey() on null
What I need:
- A reliable way to override or wrap Laravel’s cache manager to add tenant-based scoping only when a tenant is resolved, and only when the store supports tagging.
- A fallback solution for stores that do not support tagging (e.g., prefixing the cache key manually).
What’s the best approach to achieve this without breaking Laravel’s cache system or the tenancy lifecycle?
Any guidance or best practices would be greatly appreciated.
I created a custom TenantCacheManager that checks if the underlying store supports tags (supportsTags()) and falls back to manually prefixing the cache key when it doesn’t. I expected this to allow seamless tenant-specific cache usage without errors, regardless of the store driver.
However, the custom manager was still instantiated too early, before the tenant was resolved, causing tenant() to return null and crash. I also attempted to conditionally override the binding inside the service provider, but it was too late or ineffective.