Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Tenancy Laravel Package

stancl/tenancy

Automatic multi-tenancy for Laravel with minimal code changes. Supports tenant identification by hostname (including second-level domains) and avoids swapping core classes or adding model traits. Ideal for SaaS apps needing seamless tenant isolation.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Multi-tenancy Pattern: The package implements database-per-tenant isolation with minimal code changes, leveraging Laravel’s built-in features (e.g., database connections, middleware). This aligns well with SaaS architectures requiring strict tenant separation.
  • Middleware-Based Tenant Resolution: Uses middleware to dynamically switch database contexts based on hostname, subdomains, or custom resolvers, reducing boilerplate.
  • Zero-Configuration for Basic Use: No model traits or class overrides required, making it ideal for greenfield projects or migrations where minimal disruption is critical.
  • Extensibility: Supports custom tenant resolvers (e.g., path-based, header-based) and integrates with Vite, Queues, Caching, and Storage for full-stack tenancy.

Integration Feasibility

  • Laravel Ecosystem Compatibility: Works seamlessly with Laravel 10–13, PHP 8+, and supports MySQL, PostgreSQL, MariaDB, and SQLite. The package’s maturity (4.3K stars, active maintenance) reduces integration risk.
  • Database Schema Isolation: Automatically prefixes tables (configurable) or uses separate schemas/databases per tenant, avoiding shared-table anti-patterns.
  • Queue/Job Tenancy: Supports tenant-aware job processing with fixes for edge cases (e.g., queue:retry), critical for async workflows.
  • Asset Isolation: Vite and filesystem support ensures tenant-specific assets (CSS/JS) are served correctly via subdomain paths.

Technical Risk

  • Performance Overhead:
    • Middleware-based tenant resolution adds ~1–5ms latency per request (benchmark in staging).
    • Cache invalidation (e.g., tenant resolvers) may require tuning for high-scale apps.
  • Migration Complexity:
    • Existing apps with shared-table tenancy or custom database logic may need refactoring.
    • Zero-downtime migrations: Requires careful sequencing (see Integration Approach).
  • Edge Cases:
    • Impersonation: Tenant switching via middleware must handle edge cases (e.g., admin users accessing multiple tenants).
    • Queue Workers: Workers must revert to the central context post-job execution (fixed in v3.8.5 but requires testing).
  • Vendor Lock-in:
    • Custom tenant resolvers or middleware may become tightly coupled to the package.

Key Questions

  1. Tenant Identification Strategy:
    • Will hostname/subdomain-based resolution suffice, or are custom resolvers (e.g., API headers) needed?
    • How will tenant onboarding/offboarding (e.g., DNS changes) be automated?
  2. Database Strategy:
    • Separate databases (recommended for isolation) vs. schemas/tables (simpler but less isolated).
    • How will backups/restores be handled per tenant?
  3. Performance:
    • What’s the expected tenant count? Will cache warming (e.g., resolver cache) be needed?
    • Are read replicas required for scaling?
  4. Existing Codebase:
    • Does the app use shared-table tenancy or custom database logic that conflicts with stancl/tenancy?
    • Are there legacy migrations that need rewriting?
  5. DevOps:
    • How will tenant-specific configurations (e.g., .env overrides) be managed?
    • Will Docker/Kubernetes require custom networking for subdomains?

Integration Approach

Stack Fit

  • Laravel Core: Fully compatible with Laravel 10–13 (tested up to v3.10.0). Drop-in replacement for manual tenancy logic.
  • Database: Supports MySQL, PostgreSQL, MariaDB, SQLite with schema/database isolation. No ORM changes required.
  • Caching: Tenant-aware cache tags (e.g., Cache::tags()) work out-of-the-box.
  • Queues: Tenant context preserved across jobs (fixed in v3.5.0+). Requires QueueTenancyBootstrapper.
  • Assets: Vite and filesystem support for tenant-specific assets (e.g., tenant1.app/assets/).
  • Testing: Built-in support for tenant switching in tests (e.g., Tenancy::impersonate()).

Migration Path

Phase Tasks Tools/Commands
Pre-Migration Audit existing tenancy logic (shared tables, custom DB connections). php artisan tenancy:check (custom script)
Setup Install package, configure tenants table, and middleware. composer require stancl/tenancy, php artisan vendor:publish --provider="Stancl\Tenancy\TenancyServiceProvider"
Data Migration Migrate existing tenant data to isolated schemas/databases. Custom scripts or tenancy:migrate-fresh (with --step flag for safety).
Code Adaptation Update tenant-aware logic (e.g., queries, jobs) to use Tenancy::tenant(). IDE refactoring tools, manual review.
Testing Validate tenant isolation, impersonation, and edge cases (e.g., queue jobs). php artisan tenancy:test (custom), PHPUnit.
Go-Live Deploy with feature flags for tenant routing (e.g., DNS changes). Canary releases, monitoring.

Compatibility

  • Breaking Changes:
    • Laravel 9 support dropped in v3.9.0 (app must upgrade to L10+).
    • PHP < 8.0 unsupported (v3.5.3+).
  • Dependencies:
    • Requires Laravel’s database connection switching (no conflicts with custom implementations).
    • Vite: Uses tenancy:assetPathResolver for tenant-specific asset paths.
  • Customizations:
    • Override default behavior via service providers (e.g., custom tenant resolvers).
    • Extend Tenant model for tenant-specific logic.

Sequencing

  1. Staging Validation:
    • Test with a subset of tenants (e.g., 5–10) to validate performance and data isolation.
    • Simulate failures (e.g., database connection drops) to test recovery.
  2. Phased Rollout:
    • Phase 1: New tenants use stancl/tenancy; existing tenants remain on legacy system.
    • Phase 2: Migrate legacy tenants in batches (e.g., by region).
    • Phase 3: Deprecate legacy tenancy logic.
  3. Rollback Plan:
    • Maintain dual-writable setup during migration (e.g., sync data between old/new systems).
    • Use Tenancy::disable() for emergency fallbacks.

Operational Impact

Maintenance

  • Package Updates:
    • Monitor stancl/tenancy for Laravel version support (e.g., v3.10.0 added L13 support).
    • Critical fixes: Backport patches for issues like queue worker context leaks (v3.8.5).
  • Tenant Management:
    • Automate tenant onboarding/offboarding via CLI or admin panel (e.g., php artisan tenancy:create).
    • Monitor database growth (separate databases may require separate backups).
  • Logging/Monitoring:
    • Track tenant resolution failures (e.g., missing resolvers, DB errors).
    • Monitor queue job tenancy (e.g., jobs stuck in wrong tenant context).

Support

  • Common Issues:
    • Tenant not found: Validate hostname/subdomain resolvers (e.g., PathTenantResolver).
    • Queue jobs failing: Ensure QueueTenancyBootstrapper is registered (fixed in v3.5.0+).
    • Asset loading: Verify Vite resolver paths (e.g., tenant1.app/assets/).
  • Debugging Tools:
    • Tenancy::tenant() to inspect current tenant.
    • Tenancy::impersonate() for admin access.
    • php artisan tenancy:list to audit tenants.
  • Documentation Gaps:
    • Clarify impersonation limits (e.g., admin users with multi-tenant access).
    • Document backup strategies for isolated databases.

Scaling

  • Horizontal Scaling:
    • Stateless workers: Queue workers can scale horizontally (tenant context is job-scoped).
    • Database load: Separate databases reduce contention but increase backup complexity.
  • Performance Bottlenecks:
    • Tenant resolution: Cache resolver results (e.g., Cache::remember).
    • Database connections: Use connection pooling (e.g., pgsql:pool for PostgreSQL).
    • Asset delivery: CDN tenant-specific assets to reduce origin load.
  • Multi-Region:
    • Deploy tenant databases regionally (e.g., tenant1.us.db, tenant1.eu.db).
    • Use global tenant resolvers (e.g., geolocation-based).

Failure Modes

| Scenario | Impact | Mitigation

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope