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 apps with minimal code changes. Provides tenant identification (e.g., by hostname/subdomains), isolated tenant bootstrapping, and tenancy-aware database/config switching without swapping core Laravel classes or adding model traits.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Multi-tenancy Pattern: The package implements database-per-tenant isolation with minimal code changes, aligning with Laravel’s ecosystem. It leverages middleware-based tenant resolution (e.g., hostname, subdomains, or custom logic) without requiring model traits or custom database connections.
  • Laravel Integration: Designed for deep Laravel integration (e.g., Eloquent, Queues, Cache, Storage, Vite, Filesystem), reducing friction for existing applications.
  • Centralized Tenant Management: Supports tenant identification via middleware, route parameters, or custom resolvers, enabling flexible tenant switching.
  • Isolation Scope: Automatically isolates database connections, cache, storage, and queues per tenant, ensuring data and resource segregation.

Integration Feasibility

  • Zero Code Changes: Claims to require no model trait modifications or Laravel class replacements, though validation is needed for edge cases (e.g., custom query scopes, global scopes).
  • Middleware-Based: Tenant resolution happens via middleware (TenantMiddleware), making it easy to integrate into existing Laravel routing.
  • Database Agnostic: Supports MySQL, PostgreSQL, SQLite, and MariaDB, with schema management for tenant-specific databases.
  • Asset Isolation: Built-in Vite and Filesystem support for tenant-specific assets (e.g., tenant-assets:publish).

Technical Risk

  • Performance Overhead: Tenant resolution adds middleware latency. Benchmarking required for high-traffic applications.
  • Queue Handling: Queue jobs must be tenant-aware (e.g., QueueTenancyBootstrapper). Serialization of model instances may require adjustments (e.g., using IDs instead of objects).
  • Cache Invalidation: Tenant-specific cache tags must be managed carefully to avoid stale data.
  • Migration Complexity: Tenant database creation/destruction requires careful handling of migrations and rollbacks.
  • Legacy Compatibility: Dropped support for Laravel <9 and PHP <8 may impact older stacks.

Key Questions

  1. Tenant Identification Strategy:
    • How will tenants be identified (hostname, subdomain, custom logic)?
    • Will custom tenant resolvers be needed (e.g., API keys, JWT claims)?
  2. Database Schema:
    • Will shared tables (e.g., users, roles) be used across tenants, or will all data be tenant-isolated?
    • How will initial tenant database setup be automated (e.g., migrate-fresh --tenant)?
  3. Queue and Job Handling:
    • Are jobs tenant-specific, or will a central queue be used with tenant context?
    • How will job retries and failures be managed across tenants?
  4. Asset and Storage Isolation:
    • Will tenant-specific storage (e.g., S3 buckets, local paths) be required?
    • How will Vite assets be scoped per tenant?
  5. Performance:
    • What is the expected tenant resolution latency under load?
    • Will tenant database connections be connection-pooled or reused?
  6. Fallbacks and Errors:
    • How will unrecognized tenants or resolution failures be handled (e.g., 404, redirect to central app)?
    • What’s the strategy for tenant deletion (e.g., cascading drops, data archiving)?

Integration Approach

Stack Fit

  • Laravel Versions: Officially supports Laravel 10–13 (PHP 8+). Laravel 9 support dropped in v3.9.0.
  • Database Support: MySQL, PostgreSQL, SQLite, and MariaDB via custom schema managers.
  • Queue Systems: Supports Laravel Queues (Redis, Database, SQS) with tenant-aware bootstrapping.
  • Asset Pipelines: Vite and Laravel Mix integration for tenant-scoped assets.
  • Cache Backends: Redis, Memcached, and file-based cache with tenant-specific tags.

Migration Path

  1. Pre-Integration:
    • Audit existing code for global scopes, query builders, or middleware that assumes a single database connection.
    • Plan tenant identification strategy (e.g., subdomains like tenant.example.com).
  2. Installation:
    • Install via Composer: composer require stancl/tenancy.
    • Publish config: php artisan vendor:publish --provider="Stancl\Tenancy\TenancyServiceProvider".
    • Configure tenancy.php (tenant model, resolvers, database connections).
  3. Database Setup:
    • Create a central database for tenant metadata (e.g., tenants table).
    • Use php artisan tenancy:migrate to scaffold tenant databases.
    • Seed initial tenants if needed (--force flag for production).
  4. Middleware Integration:
    • Add TenantMiddleware to app/Http/Kernel.php (typically in $middlewareGroups['web']).
    • Configure tenant resolvers (e.g., HostnameTenantResolver).
  5. Testing:
    • Test tenant resolution with Tenant::resolve() and Tenant::impersonate().
    • Validate queue jobs, cache, and storage isolation.
  6. Deployment:
    • Use php artisan tenancy:setup for initial tenant database creation.
    • Monitor tenant database performance and connection pooling.

Compatibility

  • Existing Code: Most Laravel features (Eloquent, Queues, Cache) work out-of-the-box. Customizations may be needed for:
    • Global query scopes (wrap in Tenant::resolve()).
    • Custom Eloquent events (ensure tenant context is set).
    • Third-party packages (check for tenancy support).
  • Shared vs. Isolated Data:
    • Shared tables (e.g., users) require careful design (e.g., tenant_id foreign keys).
    • Isolated tables (e.g., posts) are auto-scoped to the tenant’s database.
  • Legacy Systems: May require wrappers or adapters for non-Laravel components.

Sequencing

  1. Phase 1: Central Tenant Management
    • Implement tenant model, resolvers, and middleware.
    • Set up central database for tenant metadata.
  2. Phase 2: Database Isolation
    • Migrate existing data into tenant-specific databases.
    • Test migrate-fresh --tenant for new tenant onboarding.
  3. Phase 3: Feature Isolation
    • Isolate queues, cache, and storage per tenant.
    • Validate asset pipelines (Vite, Mix).
  4. Phase 4: Rollout
    • Gradually route tenants to isolated databases.
    • Monitor performance and errors.
  5. Phase 5: Optimization
    • Tune database connections, cache strategies, and queue workers.
    • Implement tenant-specific monitoring (e.g., New Relic, Datadog).

Operational Impact

Maintenance

  • Tenant Lifecycle Management:
    • Creation: Automated via tenancy:migrate or custom commands.
    • Deletion: Use tenancy:drop or cascade drops in migrations.
    • Backup/Restore: Tenant databases must be backed up independently (e.g., mysqldump --databases tenant_db).
  • Schema Updates:
    • Run php artisan migrate for central schema changes.
    • Use migrate-fresh --tenant for tenant-specific migrations.
  • Configuration:
    • Tenant-specific configs (e.g., .env overrides) can be managed via tenant:config or filesystem paths.
  • Logging:
    • Centralized logging (e.g., Laravel Log) with tenant context (e.g., tenant_id in log channels).

Support

  • Debugging:
    • Tenant resolution issues can be debugged with Tenant::resolve() logs.
    • Queue job failures require checking QueueTenancyBootstrapper context.
    • Use Tenant::impersonate() for admin debugging across tenants.
  • Common Issues:
    • Connection Leaks: Ensure database connections are closed (e.g., DB::disconnect() in middleware).
    • Cache Stale Data: Invalidate tenant-specific cache tags on tenant updates.
    • Queue Context Loss: Verify jobs are dispatched with tenant context (e.g., Tenant::resolve()).
  • Documentation:
    • Official docs are comprehensive but may require internal supplements for custom setups.

Scaling

  • Database Scaling:
    • Tenant databases can be sharded or moved to separate servers.
    • Read replicas can be configured per tenant.
  • Connection Pooling:
    • Laravel’s database connection pooling works per tenant.
    • Monitor connection limits (e.g., max_connections in MySQL).
  • Queue Scaling:
    • Tenant-aware queue workers can be scaled horizontally.
    • Use separate queue connections for high-throughput tenants.
  • Asset Delivery:
    • Vite and Filesystem isolation may require CDN or edge caching per tenant.

Failure Modes

Failure Scenario Impact Mitigation
Tenant resolution failure 500 errors or incorrect tenant data Fallback to central app or default tenant; log resolution errors.
Database connection exhaustion Tenant app crashes Implement connection pooling; monitor and scale database resources.
Queue job context loss Jobs fail silently Use QueueTenancyBootstrapper; log job dispatch context.
Cache stampede
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport