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

Laravel Singledb Tenancy Laravel Package

roberts/laravel-singledb-tenancy

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Single-DB Multi-Tenancy: Aligns well with SaaS architectures requiring shared infrastructure but isolated data. Avoids the complexity of multi-DB setups while mitigating performance risks (e.g., row-level security, schema-per-tenant alternatives).
  • Laravel Native: Leverages Laravel’s Eloquent, middleware, and service container, reducing friction for existing Laravel applications.
  • Domain-Based Routing: Supports subdomain/tenant mapping (e.g., tenant1.app.com), a common SaaS pattern, but lacks explicit support for path-based routing (e.g., /tenant1).
  • Limitation: No built-in support for schema-per-tenant or row-level security (e.g., PostgreSQL RLS), which may be required for stricter compliance or performance isolation.

Integration Feasibility

  • Low-Coupling Design: Middleware-based tenant resolution (TenantMiddleware) and Eloquent global scopes minimize invasive changes.
  • Dependency Risk: Relies on Laravel’s core features (e.g., Route::domain(), Model::boot()). Potential conflicts if custom tenant logic exists in the base application.
  • Testing Overhead: Tenant-scoped queries require adjustments to existing tests (e.g., mocking current_tenant() or using Tenancy::impersonate()).

Technical Risk

  • Performance: Single-table inheritance (STI) or soft-deletes across tenants may impact query performance if not optimized (e.g., proper indexing on tenant_id).
  • Migration Complexity: Backfilling tenant_id on existing tables or handling legacy data requires careful planning.
  • Edge Cases:
    • Tenant Resolution Failures: No explicit fallback for invalid domains/subdomains (could expose sensitive data).
    • Concurrent Writes: Race conditions possible if tenant resolution isn’t atomic (e.g., during middleware execution).
  • Documentation Gaps: Minimal adoption (0 stars/dependents) suggests untested edge cases in production.

Key Questions

  1. Tenant Identification: How will tenants be identified (domain/subdomain/path)? Does the package support hybrid approaches?
  2. Data Isolation Granularity: Are all models tenant-scoped, or is selective scoping needed (e.g., TenantAware trait)?
  3. Fallback Logic: What happens during tenant resolution failures? Is there a "public" tenant or error handling?
  4. Performance: Are there benchmarks for query performance with 10K+ tenants? What indexing strategies are recommended?
  5. Migration Path: How will existing data be retroactively assigned to tenants? Are there tools for bulk migration?
  6. Compliance: Does the package support audit logging or tenant-specific access controls beyond isolation?
  7. Customization: Can tenant resolution logic be extended (e.g., API key-based tenants)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Ideal for Laravel 8+/Lumen applications. Compatible with:
    • Eloquent: Automatic tenant scoping via Tenancy::resolve().
    • Middleware: Integrates with Laravel’s middleware pipeline (e.g., TenantMiddleware).
    • Routing: Supports domain/subdomain-based routing natively.
  • Non-Laravel Stacks: Not applicable—hard dependency on Laravel’s service container and routing.
  • Alternatives: Compare with:
    • Stancl/Tenant: More mature, supports schema-per-tenant.
    • BeyondCode/Laravel-Permissions: For role-based tenant access.

Migration Path

  1. Assessment Phase:
    • Audit existing tenant logic (if any) and identify gaps (e.g., missing tenant_id columns).
    • Define tenant resolution rules (domain/subdomain/path).
  2. Setup:
    • Install package: composer require roberts/laravel-singledb-tenancy.
    • Publish config: php artisan vendor:publish --provider="Roberts\Tenancy\TenancyServiceProvider".
    • Configure tenancy.php (e.g., domain or subdomain resolution).
  3. Database Schema:
    • Add tenant_id to all tenant-scoped tables (use migrations or manual ALTER).
    • Ensure tenant_id is indexed: ALTER TABLE users ADD INDEX tenant_id_idx(tenant_id).
  4. Middleware:
    • Register TenantMiddleware in app/Http/Kernel.php:
      protected $middleware = [
          \Roberts\Tenancy\Middleware\TenantMiddleware::class,
      ];
      
  5. Testing:
    • Mock tenant resolution in unit tests:
      Tenancy::impersonate(Tenant::find(1));
      
    • Test edge cases (invalid domains, concurrent requests).

Compatibility

  • Laravel Version: Tested with Laravel 8+ (check composer.json constraints).
  • PHP Version: Requires PHP 8.0+ (verify with roberts/laravel-singledb-tenancy).
  • Database: MySQL/PostgreSQL/SQLite (no vendor-specific features).
  • Conflicts:
    • Custom Model Booting: May override Tenancy::boot() if not careful.
    • Route Caching: Clear cached routes if adding tenant-specific domains post-install.

Sequencing

  1. Phase 1: Proof of Concept
    • Set up a single tenant, verify isolation, and test current_tenant() helper.
  2. Phase 2: Migration
    • Backfill tenant_id for existing data (batch process to avoid locks).
    • Update all Eloquent models to support tenant scoping.
  3. Phase 3: Rollout
    • Deploy middleware and routing changes.
    • Monitor query performance and tenant resolution latency.
  4. Phase 4: Optimization
    • Add tenant-specific indexes or query caching.
    • Implement tenant-specific connection pooling (if needed).

Operational Impact

Maintenance

  • Package Updates: Monitor for breaking changes (MIT license allows forks if needed).
  • Dependency Management: Ensure compatibility with Laravel core updates (e.g., Eloquent changes).
  • Custom Logic: Extensions to tenant resolution may require maintenance if package evolves.

Support

  • Debugging: Limited community support (0 stars). Debugging may rely on:
    • Package logs (Tenancy::debug()).
    • GitHub issues (if any exist).
  • Common Issues:
    • Tenant resolution failures (e.g., misconfigured domains).
    • Query performance degradation (lack of proper indexing).
  • Fallback Plan: Document manual tenant resolution bypass (e.g., Tenancy::setTenantId()) for critical paths.

Scaling

  • Horizontal Scaling:
    • Stateless Middleware: Tenant resolution is stateless; works with load balancers.
    • Database Load: Single-DB tenancy may hit limits at scale (e.g., 100K+ tenants). Consider:
      • Read replicas with tenant-aware routing.
      • Sharding by tenant (requires custom logic).
  • Performance Bottlenecks:
    • Query Scoping: Global tenant scopes add overhead to every query. Mitigate with:
      • Tenant-specific indexes (e.g., tenant_id + created_at).
      • Query caching (e.g., Redis for frequent tenant data).
    • Tenant Resolution: Domain lookups add latency. Pre-warm tenant cache if using API gateways.

Failure Modes

Failure Scenario Impact Mitigation
Tenant resolution failure Data leakage or 500 errors Configure fallback tenant or graceful degradation.
Database connection issues All tenants affected Implement circuit breakers for DB layer.
Missing tenant_id in queries Silent data leakage Use Tenancy::ensureResolved() or CI/CD checks.
Concurrent tenant resolution Race conditions Use database transactions for critical paths.
Package regression Tenant isolation broken Fork and maintain if critical.

Ramp-Up

  • Team Onboarding:
    • Developers: Train on:
      • Tenant-aware Eloquent queries.
      • Tenancy::impersonate() for debugging.
      • Middleware customization.
    • DevOps: Document:
      • Database indexing strategies.
      • Tenant resolution latency SLOs.
      • Rollback procedures.
  • Documentation Gaps:
    • Create internal runbooks for:
      • Tenant migration steps.
      • Performance tuning (e.g., query optimization).
      • Disaster recovery (e.g., tenant data restoration).
  • Training Materials:
    • Record a demo of tenant isolation in action.
    • Share examples of tenant-scoped queries and middleware extensions.
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle