Search by

Enterprise-grade standalone Laravel multi-tenancy package for Laravel 12 & 13 — domain-based isolation across database, cache, session, filesystem, queue, mail and logs, Livewire 4 integration, and zero stancl/tenancy dependency.

0.8.4 2026-03-24 12:21 UTC

This package is auto-updated.

Last update: 2026-11-16 12:08:21 UTC


README

Standalone Laravel multi-tenancy — isolated by default, not just the database.

Tests Latest Version License: MIT PHP Laravel

  • Domain-based isolation across database, cache, session, filesystem, queue, mail and logs
  • No stancl/tenancy dependency — fully self-contained
  • Redis optional — one-time health ping, auto-fallback to the database store
  • Laravel 12 & 13, PHP 8.2+, Livewire 4
  • MIT licensed — contributions welcome

Requirements

Dependency Version
PHP 8.2+
Laravel 12.x / 13.x
MySQL / MariaDB 8.0+ / 10.4+
predis/predis optional — add it yourself if your app uses Redis
ext-redis required only for RedisBootstrapper key isolation

Quick Start

composer require artflow-studio/tenancy

php artisan af-tenancy:install --no-interaction

# Tables the isolation bootstrappers need inside each tenant database
php artisan vendor:publish --tag=af-tenancy-tenant-migrations
php artisan tenant:db migrate

php artisan tenant:create
php artisan tenancy:doctor          # verify the install is correct AND secure
APP_DOMAIN=yourdomain.com
TENANT_API_KEY=<32+ random characters>   # required — guards tenant create/delete

What "isolated" means here

One tenant must never observe or alter another's data. Database isolation alone does not achieve that: a shared cache key, a shared storage disk, or a queued job that runs in the wrong context all cross the boundary — and each of those leaks is invisible in manual testing, because under PHP-FPM the process dies between requests and hides it.

Subsystem Default Mechanism
Database ✅ database.default → the tenant connection
Cache ✅ Per-tenant prefix + tenant cache table
Filesystem ✅ tenant_public / tenant_private disks
Session ✅ Scoped cookie + tenant sessions table
Queue / jobs ✅ Tenant stamped into the payload, restored per job
Mail ✅ Per-tenant from-address and SMTP credentials
Logs ⭘ Per-tenant channel, or tenant_id on every record
Redis keys ⭘ Requires phpredis
Broadcasting ⭘ tenant_channel() helper

Two rules hold it together:

  1. Fail closed, never fall back. When tenant context is expected and cannot be established, the operation throws. Silently continuing in central context turns "we don't know whose data this is" into "serve it as the platform's" — the one failure you cannot detect from logs afterwards.
  2. Every bootstrapper forgets its cached instance. config() changes are invisible to an already-resolved singleton, so rewriting config without forgetInstance() / forgetDisk() / forgetMailers() hands the next tenant the previous tenant's object.

How It Works

Request → InitializeTenancyByDomain          (auto-prepended to the 'web' group)
  ↓
  DomainResolver::resolve($host)             cache hit ~0.5ms, or one indexed JOIN ~3ms
  ↓
  Tenancy::initialize($tenant)
  ↓
  DatabaseBootstrapper   → switch DB         (first — others read tenant settings from it)
  CacheBootstrapper      → prefix cache keys
  FilesystemBootstrapper → mount tenant disks
  SessionBootstrapper    → scope cookie + session table
  QueueBootstrapper      → tenant queue names
  MailBootstrapper       → tenant sender identity
  ↓
  [Request handled in tenant context]
  ↓
  Tenancy::end()  → bootstrappers revert in REVERSE order, DB torn down last

Queued jobs

Dispatch and execution happen in different processes, so no bootstrapper can bridge them — the tenant travels in the payload instead:

// Dispatched on acme.com; the worker restores tenant "acme" before handle() runs
ProcessInvoice::dispatch($invoice);

// Platform work stays central even when a tenant dispatched it
class SyncBillingJob implements ShouldQueue, RunsInCentralContext {}

A job whose tenant no longer exists fails rather than running against the central database.

Tenant Routes

// Tenant-scoped
Route::middleware(['auth', 'tenant.web'])->prefix('business')->group(function () {
    Route::get('/dashboard', BusinessDashboard::class);
});

// Central-only
Route::middleware(['central.web', 'auth'])->prefix('admin')->group(function () {
    Route::get('/tenants', TenantsIndex::class);
});

// Both
Route::middleware(['universal.web'])->group(function () {
    Route::get('/login', LoginPage::class)->name('login');
});

Artisan Commands

php artisan tenancy:doctor                    # isolation, security & config invariants
php artisan tenancy:doctor --tenant-schema    # also check every tenant database

php artisan tenant:create
php artisan tenant:list
php artisan tenant:delete {uuid}
php artisan tenant:health

php artisan tenant:db migrate
php artisan tenants:run "queue:prune-batches" --continue-on-error

php artisan tenancy:migrate-scope --dry-run   # domain → tenant-key storage scoping

Helpers

tenancy()                  // Tenancy singleton
tenant()                   // Active Tenant model, or null
get_current_domain()       // Current hostname
tenant_path($sub)          // Path inside the tenant's public tree
tenant_private_path($sub)  // Path inside the tenant's private tree
tenant_url($sub)           // Public URL for a tenant asset
tenant_channel('orders')   // Tenant-scoped broadcast channel (throws if central)

Testing

$tenant = makeTenant('acme');

$tenant->run(function () {
    User::create(['name' => 'Alice', 'email' => 'alice@example.com', 'password' => bcrypt('x')]);

    expect(User::count())->toBe(1);
});

The package's own suite runs standalone, on Orchestra Testbench:

composer install     # dev-only, gitignored
composer test

Documentation

docs/index.html for the interactive version, or the markdown in docs/:

00 — Index Architecture and quick links
07 — Cache, Session & Queue Queue isolation in depth
15 — Mail Isolation Per-tenant sender identity
16 — Security Model What is protected, what you must configure
17 — Tenant Scoping Key Domain vs tenant-key scoping
18 — Upgrade Guide Breaking changes
19 — File Structure Target layout and renaming plan

Outstanding work: docs/AUDIT/README.md.

Contributing

Contributions are welcome — fork it, and open a PR.

git clone https://github.com/artflow-studio/tenancy.git
cd tenancy
composer install
composer check        # style + static analysis + tests

The suite runs standalone on Orchestra Testbench; you do not need a host Laravel application to work on the package.

Before writing code, read the two rules in CONTRIBUTING.md. This package handles tenant data isolation, so a subtle bug does not throw — it quietly serves one customer's data to another. Both rules exist because the package has shipped that bug:

  1. Fail closed, never fall back. If tenant context cannot be established, throw. A catch that continues turns "we don't know whose data this is" into "treat it as the platform's", and leaves nothing in the logs.
  2. Every bootstrapper forgets its cached instance. config() changes are invisible to an already-resolved singleton — and this class of bug is invisible under PHP-FPM, appearing only under Octane or in queue workers.

Good first contributions are listed in docs/AUDIT/README.md, which tracks the outstanding work in priority order with the reasoning behind each item.

CONTRIBUTING.md Setup, conventions, PR expectations
CODE_OF_CONDUCT.md Community standards
SECURITY.md Reporting a vulnerability — never as a public issue
docs/19-file-structure.md Where things live, and why

Changelog

See CHANGELOG.md.

Credits

Built and maintained by Artflow Studio — and by everyone who has contributed.

The architecture — event-driven bootstrappers, a cached domain resolver, and reverse-order teardown — follows the design proven by stancl/tenancy, reimplemented here with no dependency on it.

License

MIT © Artflow Studio.

Use it, fork it, ship it commercially. If it saves you a bad afternoon, a star is appreciated.