Database strategies
Filament Tenancy supports two models of tenant data separation, selected by one config key — and they compose, so a single app can run both at once:
dedicated(the default) — one database per tenant. Isolation is the connection switch itself: stancl/tenancy points the runtime at the tenant's own database, tenant tables carry notenant_idcolumn, and a tenant's data can be backed up, restored, exported, or deleted as one database.shared— many tenants per database. Isolation is atenant_idrelationship scope, applied automatically by Filament — optionally hardened with PostgreSQL Row-Level Security so the database itself enforces it. Rows live in the central database (or in shared shard databases spread across servers), tenants are ready the moment they sign up, and a new tenant costs one row instead of one database.
// config/packstub-tenancy.php
'database_strategy' => 'dedicated', // or 'shared'
// or fluently, per panel
use Packstub\Tenancy\TenancyPlugin;
TenancyPlugin::make()->databaseStrategy('shared');
Individual tenants can override the app-wide strategy at creation with an isolation_mode attribute — that is the hybrid model: a shared app that still gives an enterprise customer a private database, or a dedicated app with a lightweight shared free tier.
Choosing a strategy
Both models are first-class; they optimize for different things.
dedicated |
shared |
|
|---|---|---|
| Isolation mechanism | connection switch (structural) | tenant_id scope (query-level) |
| Signup cost | database create + migrate (queued) | one row — ready instantly |
| Per-tenant backup / export / delete | dump one database | row-level queries |
| Schema migrations | once per tenant (tenants:migrate) |
once per database |
| Tenant count sweet spot | tens to thousands | thousands and up |
| Horizontal scaling | pool of database servers | pool of shared shard databases |
| Database-enforced isolation | inherent (separate databases) | optional — PostgreSQL RLS |
| Great for | B2B SaaS, compliance, data residency | high-volume signups, free tiers, B2C |
Rules of thumb:
- Choose dedicated when tenants are businesses that care where their data lives, when per-tenant backup/restore matters, or when you never want isolation to depend on every query being scoped correctly.
- Choose shared when signups are high-volume and low-friction, when thousands of mostly-small tenants would mean thousands of databases, or when your team already runs the classic
tenant_idmodel comfortably. - Choose both (hybrid) when your pricing tiers map to isolation — shared for the free tier, a private database for the enterprise plan.
The dedicated strategy (default)
This is the model the rest of the documentation describes: signup queues the CreateDatabase → MigrateDatabase → MarkTenantReady pipeline, the waiting room shows progress, and stancl's DatabaseTenancyBootstrapper switches the runtime connection per request. Nothing changes for existing installs — dedicated is the shipped default, and Filament's automatic resource scoping stays off because the connection switch already isolates every query.
Setup is covered by Installation and Quickstart; spreading tenant databases across servers is Horizontal scaling.
The shared strategy
1. Flip the strategy
// config/packstub-tenancy.php
'database_strategy' => 'shared',
From this moment, every new tenant is created database-less: the plugin stamps isolation_mode = 'shared' and stancl's create_database => false flag on the tenant, skips the database pipeline entirely, and marks the tenant ready through a queued MarkTenantReady-only pipeline. No CreateDatabase, no per-tenant migrations — signups complete in the time it takes the queue to turn around.
At runtime the plugin routes stancl's bootstrappers per tenant: a shared tenant with no shard connection skips DatabaseTenancyBootstrapper, so queries stay on the central connection where the rows actually live. (Cache, filesystem, and other bootstrappers you configured keep running — only the database switch is dropped, and only for tenants that have no database to switch to.)
2. Give tenant-owned tables a tenant_id
Tenant-owned tables live in your central migrations and carry an indexed tenant_id:
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->string('tenant_id')->index();
$table->string('name');
$table->timestamps();
});
Two notes:
- The shipped
tenantstable uses string (UUID) keys — stancl's convention — so the column is astring, not an unsigned integer. If you published the migrations with an integer tenant key, match it. - A foreign key from
tenant_idtotenants(->constrained(),cascadeOnDelete()) works as long as every tenant stays in this one database, and the cascade removes a deleted tenant's rows for you. It also ties the table to that database: a shard or a private database holds notenantsrow, sotenants:moverefuses to move a table whose rows point at the tenant table. Leave it out when shards or private databases are on the horizon, and remove a deleted tenant's rows with the listener under Deleting shared tenants, which a sharded setup needs anyway.
Each tenant-owned model then defines the relationship back to the tenant:
use Packstub\Tenancy\Models\Tenant;
class Project extends Model
{
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
}
3. Let Filament scope everything
Under the shared strategy, scope_resources_to_tenant defaults to true: the plugin calls Filament's Resource::scopeToTenant(), and every resource query is automatically constrained to the current tenant through the ownership relationship (whereBelongsTo($tenant)), while created records are automatically associated with it. If your relationship is not named after the tenant model (tenant() for the shipped Tenant model), point Filament at it:
// config/packstub-tenancy.php
'ownership_relationship' => 'organization',
Filament's scoping covers panel resources. Everything that runs outside a panel query — raw SQL, reports, artisan commands, queued jobs — must scope by tenant_id itself, exactly as in any single-database tenancy app. If you want belt-and-braces, add a global scope to your tenant-owned models keyed off tenant() / Filament's current tenant; the plugin doesn't impose one.
4. Done — unless you want more than one database
That's the whole setup for the single-database form: tenants sign up into the central database, Filament isolates them by scope, and there is nothing to provision, pool, or migrate per tenant. (An app that already runs this way, with its own Team model and team_id columns, gets here with one command: Adopting an existing app.) When one database stops being enough, add shards:
Sharded shared: many tenants per database, many databases
The database pool works under both strategies — it just places different things. Under shared, each pool member is a pre-provisioned shard database: an ordinary connection in config/database.php whose database already exists and is already migrated. New tenants are load-balanced across shards with the same strategies (least-tenants, round-robin, weighted), and the placement is persisted on the tenant as tenancy_db_connection plus tenancy_db_name — with those two attributes set, stancl's stock DatabaseTenancyBootstrapper connects each request to the right shard, and inside the shard the tenant_id scope isolates as before.
1. Provision the shards
Each shard is a normal database you create and migrate yourself — shards hold the same schema as your central tenant-owned tables:
CREATE DATABASE tenant_shard_1;
// config/database.php
'shard_1' => [
'driver' => 'mysql',
'host' => env('SHARD_1_HOST', '10.0.1.10'),
'port' => env('SHARD_1_PORT', 3306),
'database' => 'tenant_shard_1', // must exist — validation enforces it
'username' => env('SHARD_1_USERNAME'),
'password' => env('SHARD_1_PASSWORD'),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
],
Run your tenant-owned migrations against every shard whenever they change — shards migrate like databases, not like tenants:
php artisan migrate --database=shard_1 --path=database/migrations/shared
php artisan migrate --database=shard_2 --path=database/migrations/shared
(Keeping shard-schema migrations in their own directory, e.g. database/migrations/shared, makes this a clean loop — and keeps central-only tables out of the shards.)
2. Enroll them in the pool
'database_pool' => [
'enabled' => true,
'connections' => ['shard_1', 'shard_2'],
'strategy' => 'least-tenants',
'weights' => [],
],
Boot validation checks every member as usual, plus one shared-strategy rule: each member must have a database configured — that name is what gets persisted per tenant as tenancy_db_name.
tenants:pool shows the tenant distribution across shards exactly as it does across servers, and tenants:pool --check probes shard reachability instead of CREATE DATABASE privileges — nothing is ever created on a shard, so the placement user needs no admin rights.
3. Scale out the same way
Adding shard capacity is the same runbook as adding a server in dedicated mode: create + migrate the new shard database, add its connection, append the name to the pool, deploy everywhere (queue workers too), and least-tenants fills it first. Placement is sticky — existing tenants never move on their own — and a tenant can be pinned to a specific shard by creating it with an explicit tenancy_db_connection + tenancy_db_name.
Note that the shard user does need day-to-day query privileges on its shard, and every app host (web and workers) needs the shard connections defined — the same fleet-wide config rule as the dedicated pool.
Row-Level Security: database-enforced isolation (PostgreSQL)
Because the shared strategy puts a tenant_id on every tenant-owned row, it unlocks a third layer most tenant_id apps never get around to: PostgreSQL Row-Level Security. With RLS enabled, isolation is enforced by the database itself — a query that forgets its scope (a raw report, a hand-written join, a debugging session in Tinker) physically cannot return another tenant's rows, because Postgres filters them out before the app ever sees them.
The layers complement each other rather than compete:
- Filament's relationship scope (on by default under the shared strategy) drives the UI: it constrains resource queries and associates newly created records with the current tenant.
- RLS policies are the backstop: whatever the query looks like, the database only yields rows whose
tenant_idmatches the current tenant.
stancl/tenancy v4 ships the entire RLS toolchain, and the shared strategy composes with it directly — shared tenants keep every bootstrapper you configure (the plugin only removes the database switch), which is exactly the seam RLS plugs into.
1. Configure the RLS user and session variable
// config/tenancy.php
'rls' => [
'manager' => Stancl\Tenancy\RLS\PolicyManagers\TableRLSManager::class,
'user' => [
'username' => env('TENANCY_RLS_USERNAME'),
'password' => env('TENANCY_RLS_PASSWORD'),
],
// Must be namespaced ('app.', 'my.', …) — the global namespace is
// reserved for server configuration.
'session_variable_name' => 'app.current_tenant',
],
This is one database user for all tenants — a deliberately non-owner, non-superuser role that RLS policies actually apply to (table owners and superusers bypass RLS). Your central connection keeps using the privileged user for migrations and central-only tables.
2. Generate the policies
php artisan tenants:rls
The command creates the RLS user if it doesn't exist and generates a policy for every table related to the tenants table — including indirectly related ones. The default TableRLSManager walks foreign keys, so comments → posts → tenants gets a policy that scopes comments through their post's tenant:
CREATE POLICY posts_rls_policy ON posts USING (
tenant_id::text = current_setting('app.current_tenant')
);
(Prefer declaring RLS-protected models explicitly? Swap in TraitRLSManager and mark models with stancl's RLSModel concern.)
3. Swap the bootstrapper
// config/tenancy.php — a pure shared + RLS app
'bootstrappers' => [
Stancl\Tenancy\Bootstrappers\PostgresRLSBootstrapper::class,
// ...cache/filesystem bootstrappers as needed
],
On tenancy initialization, PostgresRLSBootstrapper reconnects as the RLS user and runs SET app.current_tenant = '<tenant key>'; on end, it resets the variable and returns to the central connection. From that moment every query in tenant context is filtered by the database, no matter who wrote it.
Caveats worth knowing
-
PostgreSQL, single-database form. Stancl's stock RLS bootstrapper builds the tenant connection from the central connection, so it targets the shared strategy's single-database form. RLS on shards is possible but bring-your-own: create the RLS user and policies per shard and register a small custom bootstrapper that applies the shard connection + RLS credentials together.
-
Hybrid fleets need explicit routing. In a mixed app, dedicated tenants must get
DatabaseTenancyBootstrapperand shared tenantsPostgresRLSBootstrapper— set your own router and the plugin steps aside (it never overwrites an app-owned closure):use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\PostgresRLSBootstrapper; tenancy()->getBootstrappersUsing = fn ($tenant) => $tenant?->isolation_mode === 'dedicated' ? [DatabaseTenancyBootstrapper::class] : [PostgresRLSBootstrapper::class]; -
Connection poolers. The tenant key lives in a Postgres session variable. Behind a transaction-pooling PgBouncer, session state doesn't stick to your connection — use session pooling for the RLS connection (or route it around the pooler).
-
Keep Filament's scoping on. RLS filters reads and blocks cross-tenant writes, but it doesn't assign
tenant_idto new records — Filament's ownership relationship does that on create. They're better together.
Hybrid fleets: isolation_mode per tenant
The app-wide strategy is a default, not a straitjacket. Any tenant can be created with the other model:
use Packstub\Tenancy\Models\Tenant;
// A private database for an enterprise tenant inside a SHARED app —
// the full provisioning pipeline runs, just for this tenant:
Tenant::create([
'name' => 'Enterprise Co',
'slug' => 'enterprise',
'isolation_mode' => 'dedicated',
]);
// A shared-model tenant inside a DEDICATED app — database-less, instantly ready:
Tenant::create([
'name' => 'Free Tier Co',
'slug' => 'free-tier',
'isolation_mode' => 'shared',
]);
isolation_mode persists via stancl's VirtualColumn (data column) — no schema change needed — and the plugin routes everything off it and the create_database flag it implies: the provisioning pipeline, pool placement, bootstrapper selection, and deletion behavior all follow the tenant, not the app default.
Two placement notes for hybrids:
- In a shared app, a
dedicatedtenant is not placed by the pool (pool members are shards, notCREATE DATABASEservers). Give it an explicittenancy_db_connectionpin pointing at a server connection — the same pin data-residency tenants use — or let it follow stancl'stemplate_tenant_connection. A dedicated tenant on a database that already exists (tenancy_create_database => false) always needs the pin in a shared app: without atenancy_db_connection, a tenant without a database of its own runs on the central database there, whatever itsisolation_mode. - In a dedicated app, a
sharedtenant lives in the central database (there is no shard pool to place it on).
Combined with pins, this covers the full spectrum in one app: free tier in the central database, standard tier on shards, enterprise on a private database, regulated customers on a private database on their own server.
Deleting shared tenants
Deleting a dedicated tenant drops its database. Deleting a shared tenant deliberately does not touch the shared database — stancl's DeleteDatabase job skips database-less tenants, which is exactly what protects a shard holding hundreds of other tenants.
That means the tenant's rows are your responsibility. The clean options:
cascadeOnDelete()foreign keys from every tenant-owned table totenants(single-database form only — the cascade lives where the rows live, and such a table cannot be moved to a shard), or- a
deletingobserver /TenantDeletedlistener that purges rows bytenant_id— required for sharded setups, where the rows live in a different database than thetenantsrow:
use Stancl\Tenancy\Events\TenantDeleted;
Event::listen(TenantDeleted::class, function (TenantDeleted $event) {
$tenant = $event->tenant;
if ($tenant->getInternal('create_database') !== false) {
return; // dedicated tenant — DeleteDatabase already dropped its DB
}
$connection = $tenant->getInternal('db_connection'); // null = central
DB::connection($connection)->table('projects')->where('tenant_id', $tenant->getTenantKey())->delete();
// ...one line per tenant-owned table, or your own cascade helper
});
Moving a tenant between modes
Because shared-model tables carry tenant_id everywhere, a "promotion" is a data move, not a schema change: a tenant_id scope is harmless in a database that contains one tenant. tenants:move does the move. It copies every table on the source that has the tenant column, in chunks, into the target database, checks the copy there (every primary key, or the content of every row for a table without one), flips the tenant's placement (tenancy_db_connection, tenancy_db_name, isolation_mode), and only then deletes the source rows it checked. A failure before the flip leaves the tenant where it was. If deleting the old rows fails after the flip (a trigger or a permission on the source, say), the delete is rolled back: the tenant already runs on the target, nothing was deleted from the source, and the command names the rows to delete once the cause is fixed. The command says which of three cases it ended in: the delete rolled back (the usual one), the delete's outcome is unknown (the connection dropped at commit; check the source before deleting anything), or the delete went through and a later step failed.
The tenant column is tenant_id on a fresh install. On an app that adopted the plugin it is the app's own key, the membership.tenant_key that tenancy:adopt wrote (team_id for a Team model with a team_user pivot). An app adopted without a pivot keeps tenant_id there, so pass --column=team_id when its tables use team_id. --column= names any other column too. One move keys rows by one column, so when such an app also has tables keyed only by stancl's tenant_key_column (tenant_id, a newer table on stancl's BelongsToTenant, say), a move without --column refuses and names them, since their rows would stay on the source where the tenant no longer reads after the move. Pass --column=team_id to move the team_id tables anyway (the plan lists the tenant_id tables it leaves behind, for you to copy over), or --exclude= the ones that stay on the source by design. Either way, a tenant_id table whose rows reference moved rows through a foreign key still refuses the move (see below).
--to= takes a connection name from config/database.php, or the word central. The central connection's own name is refused with a hint to use central: a tenant moved to central keeps no connection or database of its own (tenancy_db_connection and tenancy_db_name are cleared), and a move to central is always --mode=shared.
Central → shard (the first scale-out of an app that started single-database):
php artisan tenants:move acme --to=shard_2
Shared → dedicated (customer upgraded to a private database): create an empty database on the server you want, run the shared-schema migrations against it, then point the move at it. --to is the server connection, --database the database on it:
php artisan tenants:move acme --to=tenant_pool_3 --database=tenant_acme --mode=dedicated
Dedicated → shared is the mirror image: --to=shard_2 --mode=shared copies the rows into the shard, and the old private database stays behind for you to drop. The command tells you whether it is empty, or names the tables that still hold rows (tables the move did not take), so you can check them first; with --keep-source it says nothing about dropping it.
Back to central: --to=central (always shared).
Before every move, --dry-run prints the tables and row counts it would touch, and says when the real move would be refused (the tenant's rows already on the target without --replace, keys other tenants use there), exiting with code 1 then. A real run checks the same before it asks for a confirmation. A non-interactive run (a deploy script, a scheduled job) cannot confirm, so it needs --force.
The target must already hold every table, with every column the source table has: the command refuses a table the target lacks and a table that lacks columns, naming them (pass --exclude= to leave a table on the source on purpose, --tables= to move a subset). Within one database family (PostgreSQL to PostgreSQL, MySQL or MariaDB to either) it also compares each copied column's full type, its character set and collation, and on PostgreSQL the base type of a domain. Only changes proven lossless pass: the same type spelled another way (an integer's display width such as int(11) and int, year(4) and year, character varying and varchar), MariaDB's uuid into char(36), MySQL's json into longtext, a double(8,2) (Laravel 10's float()) into double, and widenings of the same kind (varchar(100) into varchar(255) or text, int into bigint, decimal(8,2) into decimal(12,2), datetime into datetime(6), a MySQL float into double, an enum that gains values). A narrowing is refused, invoices.total (numeric(12,4) → numeric(12,2)) say, since the copy would round or cut those values, and so is anything else, because it can rewrite values on the way in: char(36) into MariaDB's uuid (it lowercases), a wider binary (it pads with zero bytes), enum values in another case, a set in another order, a signed number into an unsigned one, another character set or collation, timestamp into timestamp with time zone. Once you have checked that the target holds every value, --allow-type-drift skips this comparison. A nullable column going into a NOT NULL one is refused either way, flag or not, on every driver and between families too, whether or not the target column has a default: a default never stands in for an explicit NULL (PostgreSQL, SQLite and a strict MySQL refuse the row, a MySQL connection that is not strict stores the default instead, silently). SQLite stores what it is given, and between two families the types are not compared, so check those schemas yourself. The plugin's own central tables (the tenant table and its membership pivot, tenants and tenant_user or an adopted app's teams and team_user, plus domains, tenant_resources, handoff_tokens, session_grants, migrations) are never moved even though some carry the tenant column. A table of your own whose rows belong on the central database goes in --exclude: billing records keyed by tenant, or Jetstream's team_invitations, which carries team_id but is read by Jetstream's central invitation-accept route. If an earlier move stopped halfway, the target still holds that tenant's rows and the command refuses; --replace deletes them first, children first, in one transaction. --keep-source leaves the source rows in place after a verified copy, for a look before you delete them yourself. --chunk= sets the rows per batch (500 by default); a batch is split further when one statement would pass the driver's bound-parameter limit (65,535 on PostgreSQL and MySQL).
Rows that stay behind must not point at rows that move. A table without the tenant column that references a moved table through a foreign key (a post_tag pivot, order_items keyed by its order_id), and an excluded table that does, would be left pointing at rows gone from the source, while the tenant runs on the target without them. The same goes for a table that stays on the source by design, such as a users.current_project_id pointing at a moved project, and for the plugin's central tables, such as a teams.default_project_id of your own. What is not checked is a foreign key between two moved tables that crosses tenants (another tenant's comments.post_id pointing at this tenant's post): rows of one tenant that reference another's are outside the tenancy model, so check for them yourself if your schema allows them. Triggers on the target that rewrite inserted values are not seen either: the check compares keys, not the values a trigger changed. So the plan counts this tenant's rows in such tables, composite foreign keys included, and refuses, naming each table with what to do about it. A table of the tenant's data gets the tenant column (filled from its parent) so it moves with the tenant. An excluded table that has the column moves with the rows it references. A table that stays (users, say) has those references cleared or re-pointed, or that foreign key dropped, before the move. --exclude does not help, since the rows they reference still move. A reference without a foreign key constraint cannot be seen, so check tables like that yourself.
Source and target are compared by what the two connections actually reach (the server, the database and, on PostgreSQL, the schema), not by how their config spells it, so a second connection name for the source database is refused instead of copied onto itself: localhost for 127.0.0.1, a socket, a url, a MySQL or MariaDB database name in another case on a server that folds names (lower_case_table_names 1 or 2, the macOS and Windows default), or a SQLite file under another path, symlink or case. Another schema of the same PostgreSQL database counts as another place. A connection configured with a url that names a database cannot take --database=: the url's database wins in Laravel, so the command refuses and says which database the connection reached. Every query of a move runs on the connection's write host: a read replica in the config is left out, since a replica that lags would hide rows from the copy and the check. On MySQL and MariaDB the move's sessions run at time_zone = '+00:00', whatever the app's connections are configured with: a TIMESTAMP is converted through the session's zone on the way out and in, so two servers in different zones would otherwise shift every one of them. DATETIME is never converted, and PostgreSQL hands a timestamptz over with its offset.
Rows keep their primary keys when they move (child rows reference them), so the target must not already use those keys for other tenants. The plan checks the primary key (single or composite) and every plain unique index that does not include the tenant column, and refuses with the count of taken keys; auto-increment ids handed out by two databases independently will collide sooner or later, so an app that plans to move tenants between populated databases gives its shared tables UUID or ULID keys. A partial unique index (unique (email) where deleted_at is null) or an expression one (unique (lower(email)), a MySQL functional index) cannot be counted from its columns, so the plan and --dry-run name it instead, and it is checked only during the copy: a clash stops the copy before the tenant moves, and --replace restarts it once you have dealt with the clashing row. A unique index on a column only the target has is left to the copy as well; the moved rows get that column's default.
Tables are copied parents first and deleted children first, following the foreign keys between them. MySQL and SQLite run the copy and the deletes with foreign key checks off. PostgreSQL checks foreign keys on every insert for a normal role, so a foreign key that points at rows not copied yet (a self-reference such as categories.parent_id, or two tables that reference each other) is inserted as NULL and filled in by a second pass once the referenced rows are there, and the check after the copy covers that pass too. That needs the column nullable and its table to have a single-column primary key; a constraint declared DEFERRABLE is deferred instead. Any other such foreign key is refused in the plan, with the table and constraint named. A moved table's foreign key into a table that stays behind (a user_id pointing at users) is checked the other way round: the plan refuses when the target does not hold the referenced rows, on every driver. See Foreign keys that cross the tenant boundary.
On PostgreSQL, every serial and identity column on the target (not only a single-column primary key: an invoice_no serial, a serial inside a composite key) has its sequence advanced past the moved values before the first row is copied, so other tenants inserting on a live shard never take one of them, and again after each table. A sequence is never moved back: a shard whose counter is already further keeps it. GENERATED ALWAYS AS IDENTITY keys are inserted with OVERRIDING SYSTEM VALUE, and generated columns are left for the target to compute. A partitioned table moves through its parent, so each row lands in the matching partition on the target; table inheritance (inherits) is refused, since copying through the parent would leave a child's own columns behind.
--mode=dedicated is refused when the target is a pool member's own database or another tenant's database: a dedicated tenant needs a database of its own (--database=). Any move is refused onto a database the plugin created for another tenant, since deleting that tenant would drop it with the moved rows in it, and onto another dedicated tenant's private database. A shard stays open to shared moves even when the pool placed a dedicated tenant without a database of its own there.
After a move the tenant's tenancy_create_database is false whatever it was, so deleting the tenant later never drops the target database: a shard holds other tenants, and a private database the plugin did not create is yours to drop. Every other tenancy_db_* attribute (a tenancy_db_username, tenancy_db_password, tenancy_db_host or tenancy_db_port a permission-controlled database manager stored for the old database) is removed, since stancl merges them over the target connection's template at runtime, and the command checks that the connection the runtime builds from the saved placement reaches the target before it deletes anything. The placement is written on a fresh read of the tenant row, so attributes changed while the rows copied (a billing webhook, say) are kept.
On SQLite, a shard's file lives under database_path() (or SQLiteDatabaseManager::$path) and is stored by its file name, because stancl's SQLite manager resolves a tenant's database by name under that directory: a connection whose database is an absolute path to a file there works as is, and a file anywhere else is refused, with where to put it.
On MySQL and MariaDB, index the tenant column of every table on a shard (foreignId('team_id')->constrained() indexes it already; a plain string('tenant_id') column is not indexed unless you add ->index()). The source delete locks the tenant's rows of a table without a primary key, and of a table that tables staying behind reference, until it commits; without an index on the tenant column InnoDB locks every row it scans, so other tenants' writes to that table wait until the delete is done. PostgreSQL locks the tenant's rows only.
The move is windowed and explicit by design. While it runs the tenant is read-only for everything that goes through the plugin (below): its panel, its queued jobs, its commands. Writes that reach the database another way (a cron script with its own connection, a second app on the same database) are not held back, so stop those yourself (the confirmation prompt says so too). A move is a copy, and what changes on the source meanwhile is not carried over. Here is what the command detects when something slips through:
- A row added or deleted while the rows copy fails the check after the copy (the keys on the target must match the source's), and the source is left untouched. Re-run with
--replaceonce writes have stopped. - On PostgreSQL, a foreign key that cascades (or sets NULL or a default) on delete between moved tables, a self-reference such as threaded replies included, could take along a row written after the check when its parent is deleted. So the parents' rows are locked when the source delete starts, which holds back any new child until the delete is done, and a child row that was not checked cancels the whole source delete.
- A row in a table that stays on the source (a pivot without the tenant column, say) that comes to reference a moved row during the move cancels the whole source delete, like at plan time: the moved rows are locked and the references counted again right before they are deleted.
- A model listener that cancels the save of the new placement (a
savingorupdatinglistener that returnsfalse) stops the move before anything is deleted, and a placement that reads back as anything but the target (a listener that rewrote it) stops it too. - A row written after that check stays on the source. The checked rows are deleted from the source, and the command counts what is left of the tenant in every moved table afterwards: anything there was written during the move, so it exits with an error that names the tables and counts, for you to copy those rows over. Nothing is lost. Copy them by hand (select them on the old database by their keys, insert them on the new one, then delete them from the old one); the tenant already runs on the target, so do not run the move again from the old database with
--replace: that is a move back, and it starts by deleting the verified copy on the target. - A table without a primary key (a pivot, a log) is checked by content: a fingerprint of the tenant's rows, every copied column of every row, must be the same on both sides, so a row added, deleted, changed or read twice during the copy fails the check and leaves the source untouched. Its source rows are deleted by the tenant column, so right before that they are fingerprinted again, after every one of them is locked (on PostgreSQL, MySQL and MariaDB; SQLite has no row locks, and a write that commits in between makes the delete itself fail). If anything was written, changed or deleted since the check (a pivot
sync(), say), the whole source delete is cancelled: the tenant runs on the target, and the command tells you to copy the changes over and then delete the tenant's rows from the source. A write that arrives while the rows are locked waits for the delete to finish instead: an insert then stays on the source, reported like any row written after the check when it lands before the command's last count, and an update or delete finds the row gone, with the copied version on the target. That short window is one more reason to stop writes. A composite primary key with a column that can hold NULL (SQLite allows that) is treated the same way. Values are compared as the database driver returns them, so a move between two different engines (MySQL to PostgreSQL) can see equal rows as different and refuses; give such a table a primary key.
What it cannot detect: an update, during the move, to a row of a table with a primary key that was already copied (the target keeps the values it copied), and a row deleted on the source between the check and the delete in such a table (it stays on the target). The plugin never moves data behind your back, the same policy as moving a tenant between servers.
Scheduling a move
The right window is the tenant's quiet hour, not the operator's working hour. --at records the move and leaves:
php artisan tenants:move acme --to=shard_2 --at="2026-10-18 02:00"
The time is in the app's timezone and must be to come. The plan runs now, so a move that would refuse (a table the target lacks, keys other tenants use there) is refused now, not at two in the morning, and the plan runs again when the move starts, so rows written in between go along. One scheduled move per tenant; php artisan tenants:move:cancel acme cancels it while it waits (a running move cannot be cancelled: the mover leaves the tenant where it was on any failure before the flip, and finishes on its own otherwise). Every tenants:move option goes with the record (--mode, --database, --tables, --exclude, --replace, --keep-source, --chunk, --allow-type-drift).
php artisan tenants:move:due dispatches MoveTenantJob for every scheduled move whose time has come. The plugin puts that command on Laravel's scheduler every minute, so a production app that runs schedule:run from cron needs nothing else; set moves.schedule to false in config/packstub-tenancy.php to place the command yourself. The scheduler, not a delayed job, decides when a move runs: a queue delay is capped at 15 minutes on SQS and lost on a restart with some drivers. The job is unique per tenant, so two records for one tenant, or a scheduler tick while a move runs, never move it twice; it runs on moves.queue (the default queue when null) with moves.timeout seconds (3,600 by default) before the worker gives up on it, and it never initializes tenancy, so the read-only guard it causes never applies to its own writes. Keep a queue worker running for that queue, or the due moves wait on it.
When a move ends, Packstub\Tenancy\Events\TenantMoveFinished is dispatched with the record (status done or failed, error when it failed). A move started from the panel (#23) records who started it (initiated_by as user:<id>), and that user gets a Filament database notification with the outcome, when the app has the notifications table; a move started from the terminal notifies nobody, the event is there for anything else.
Moving a tenant from the panel
Once the schema is movable, a move is an operator's task, so the plugin ships it as a Filament action for the operator's console (a central panel whose resource lists the tenants):
use Packstub\Tenancy\Filament\Actions\MoveTenantAction;
// In the tenant resource's table:
->recordActions([MoveTenantAction::make()])
->toolbarActions([/* ... */])
// Or in a page header, with the record named:
MoveTenantAction::make()->record(fn () => $this->getRecord())
The action is shown only when Gate::allows('move', $tenant): add a move(User $user, Tenant $tenant): bool method to the tenant's policy, and only those users see it. It opens a three-step modal:
- Target: the central database, every pool member and any other connection from
config/database.php(the central connection and stancl'stenanttemplate are left out;->targets(['shard_2' => 'EU shard'])replaces the list), the isolation mode after the move (keep, shared, dedicated) and, for a dedicated move, the database name. - Preview: the plan runs, as
tenants:move --dry-rundoes. The tables with their row counts, the tenant column, an estimate of the read-only window, and the tables a move by this column leaves behind. A plan that refuses (a table the target lacks, keys other tenants use there, a foreign key across the boundary) stops here, with the command's message on screen, so a move that would refuse is never scheduled. - When: now, or a date and time in the app's timezone, then the read-only window named once more.
Confirming records a move for the signed-in user (initiated_by as user:<id>): a move for now is dispatched to the queue at once as MoveTenantJob, a move for later waits for tenants:move:due (Scheduling a move). Either way the job plans again when it starts, the tenant is read-only while the rows copy, and the user gets a Filament database notification when the move is done or has failed. A tenant with a move that waits or runs cannot be given another until it is cancelled or done.
Packstub\Tenancy\Filament\RelationManagers\MovesRelationManager lists a tenant's moves on the resource's view or edit page (status, target, progress, when, by whom, the error of a failed one), with the Move action in its header and Cancel on a move that waits; it polls every five seconds while one runs. Register it in the resource's getRelations().
The pool board
Packstub\Tenancy\Filament\Widgets\DatabasePoolBoard shows who sits where: a column per place a tenant can live (the central database under the shared strategy, every pool member with "next tenant lands here" on the one the pool would pick, and every other connection tenants are pinned to), a card per tenant with its status, its database name for a dedicated one, and a pulse while it moves. Each column lists its first 50 tenants by name and counts the rest; the search narrows every column. Register it in the operator's central panel next to DatabasePoolOverview:
->widgets([
\Packstub\Tenancy\Filament\Widgets\DatabasePoolOverview::class,
\Packstub\Tenancy\Filament\Widgets\DatabasePoolBoard::class,
])
Dragging a card onto another column opens the Move action with that target filled in: the same preview, refusals and confirmation, never a silent move, and the card stays where it was until the move has run. Cards are draggable only for a user the move ability allows, and a card that moves or waits for a move is not. The widget hides itself while the pool is disabled under a dedicated strategy, since there is nowhere to move to then.
Read-only while the tenant moves
Every move writes a row in tenant_moves on the central database ($tenant->moves(), $tenant->currentMove(), $tenant->isMoving()): where it goes, the tables and row counts it was planned with, its progress, when it started and ended, and the error when it failed. tenants:move opens the record right before the copy and closes it when the move is done or has failed, so the record is the one place the rest of the plugin reads to know that a tenant is moving.
While a record is running, every request, queued job and artisan command that initializes tenancy for that tenant gets a guard on the connection the tenant's rows are read from (the shard or private database for a tenant with one, the central connection for a shared tenant on central): an INSERT, UPDATE, DELETE or TRUNCATE that names one of the move's tables throws TenantReadOnlyException before it reaches the database. Reads go through, and so do writes to every other table (sessions, notifications, users, the tenant table), so the tenant stays usable and everyone stays signed in. The guard sits on the connection, not on the models, so a pivot attach(), a sync() and a raw statement are refused like an Eloquent save; a write to another table that only reads a moved one in a subquery is refused as well. It is armed per process on TenancyInitialized and released on TenancyEnded.
What the refusal looks like: in a Filament action, form or table (a Livewire request) a persistent danger notification, "Read-only while moving", and the page keeps its state; in a plain web request a redirect back with the same notification flashed; for a JSON client a 423 Locked; in a job or a command the exception itself, for the caller to retry once the move is done (check $tenant->isMoving() first in a job that runs often). The tenant's panel shows a banner at the top of every page for the whole move, with the share of rows copied and an estimate, and before a scheduled move the window it will be read-only in. The banner is packstub-tenancy::filament.move-banner (publish the views to change it) and its text is in the moves translation file.
Not covered: writes that do not initialize tenancy (a cron script with its own database connection, another app on the same database), which the detection list above is for.
Foreign keys that cross the tenant boundary
A database-level foreign key joins two rows in one database. Once a tenant can be pooled on a shard, moved, or given a private database, any foreign key between a tenant's rows and rows that stay on the central database is one that cannot hold for that tenant. The rule that keeps tenants movable: design the schema as if every tenant already lived in its own database, even while it sits on central. Sort each foreign key by where its two rows can end up:
- Tenant row → tenant row (
order_items.order_id → orders,categories.parent_id → categories). Keep them: the rows move together, and the constraint holds on every database. The one requirement is that every table of tenant data carries the tenant column, pivots included: apost_tagwithouttenant_idis refused by the move, and the fix is to add the column (filled from its parent), never to drop the key. - Tenant row → central row (
posts.user_id → users,orders.plan_id → plans, and thetenant_id → tenantsthat->constrained()adds). Two sound options. A plain reference: keep the column and its index, drop the constraint. Eloquent does not need it:belongsTo(User::class)queries on theUsermodel's own connection, so$post->userresolves on central from any shard or private database; integrity moves to the app, adeletinglistener onUserthat clears or reassigns, or soft-deleted users that are never hard-deleted. Or resource syncing: theusersrows a tenant needs are mirrored into its database,posts.user_idpoints at the local copy, and the constraint stays. Plain references suit small lookups (plans, feature flags); syncing suits users and anything the tenant database must join locally. - Central row → tenant row (
users.current_project_id → projects, ateams.default_project_idof your own). Never as a constraint, and ideally not as a column on central at all: a central row is shared by every tenant, and the row it points at can be in any database. Keep that pointer on the tenant side (aproject_usersettings row that carriestenant_id), or as a plain(tenant_id, project_id)pair on central that the app validates.
Only the crossing keys trade engine-enforced integrity for portability: cascades become listeners, and an orphan check (a scheduled command that counts references with no row behind them) replaces what the engine did. Within-tenant keys keep all of it.
tenants:move checks both directions in the plan, before anything is copied, and refuses with each table named and what to do about it:
- From a table that stays into a moved table (above): the rows that would be left pointing at rows gone from the source are counted, and the fix depends on the table: give it the tenant column, move it with the rows it references, or clear the references.
- From a moved table into a table that stays, on every driver: the plan reads the tenant's referenced keys and looks them up on the target. A reference the target can satisfy passes (a synced
usersrow, a lookup table migrated with its rows), a NULL reference needs no row, and a key the target does not hold refuses the move, naming the foreign key, the row count and the fix: drop the constraint and keep the column as a plain reference, or sync the table into the target; a reference into an excluded table that carries the tenant column says to move that table instead, and one into the tenant table says to drop that key, since a shard holds notenantsrow. Without this check PostgreSQL would refuse the copy half-way, and MySQL and SQLite, which copy with their checks off, would leave the reference dangling.
A reference without a constraint (a bare user_id column) cannot be seen by either check, and needs no change.
On an adopted app. An app that grew up single-database usually has these keys everywhere: foreignId('team_id')->constrained() on every table, users.current_team_id, Jetstream's team_invitations. tenancy:adopt lists every foreign key that crosses the boundary, in both directions, as one of its next steps, so you know before the first move; nothing has to change on the day you adopt, since every row still lives in one database. The steps, in order:
php artisan tenancy:adopt "App\Models\Team"and read the step "Foreign keys that cross the tenant boundary". (Note thatusers.current_team_id → teamsis not in it:teamsis the tenant table, which stays on central withusers.)- Before the first move, a migration for the keys that point at central:
$table->dropForeign(['team_id'])and$table->dropForeign(['user_id']), keeping the columns and their indexes (->constrained()indexed them already). Move cascades fromteamsinto aTenantDeletedlistener (Deleting shared tenants); a cascade fromusersbecomes adeletinglistener onUser. - For the keys that point from central at a team's rows, move the pointer into the team's own tables, or clear it for the tenant right before its move.
php artisan tenants:move acme --to=shard_2 --dry-run: the plan says whether anything still crosses, and exits 1 if the real move would be refused.php artisan tenants:move acme --to=shard_2.
On a fresh app, leave the tenant_id → tenants key out from the start (step 2) and reference central rows (user_id) as plain columns; the move then has nothing to refuse.
Testing your setup
The package's own suites are templates for yours:
tests/Feature/DatabaseStrategyTest.php— strategy defaults, per-tenantisolation_modeoverrides, scoping defaults.tests/Feature/SharedDatabaseStrategyTest.php— shared tenants staying on the central connection, hybrid dedicated tenants keeping the full bootstrapper stack.tests/Feature/SharedDatabasePoolTest.php— shard placement, two tenants sharing one database at runtime, deletion leaving the shard intact,tenants:pool --checkunder the shared strategy.
The pattern: set packstub-tenancy.database_strategy (in defineEnvironment, so boot-time wiring sees it), create tenants through your real signup path, then assert on isolation_mode, getInternal('create_database'), getInternal('db_connection') / getInternal('db_name'), and — for runtime behavior — DB::connection()->getDatabaseName() inside tenancy()->initialize($tenant).
FAQ
Does switching the strategy affect existing tenants?
No. The strategy is applied at tenant creation — existing tenants keep their isolation_mode, connections, and databases. Switching the config only changes what new signups get, so you can migrate a fleet gradually (or never).
Can I use the shared strategy without Filament's resource scoping?
Yes — set scope_resources_to_tenant => false explicitly and bring your own isolation (global scopes, RLS policies). The strategy still gives you database-less signups, bootstrapper routing, and shard placement; you own the query-level isolation.
Do shared tenants still fire stancl events and initialize tenancy?
Yes. Filament's resolved tenant is bridged into tenancy()->initialize() as always, so tenant(), tenant-aware cache/filesystem bootstrappers, and your own listeners work in both strategies. Only the database connection switch is skipped, and only for tenants without a database.
Can shards and the central database share a server?
Yes — shards are just connections. A common starting topology is central + shard_1 on one server, with new shards added on new servers as you grow.
What about PostgreSQL Row-Level Security?
Fully supported — stancl v4 ships the toolchain (tenants:rls, PostgresRLSBootstrapper, FK-walking policy generation) and the shared strategy plugs straight into it, giving you database-enforced isolation on top of Filament's scoping. See Row-Level Security.
Next steps
- Setting up from scratch? Installation → flip
database_strategybefore your first signup. - Spreading dedicated tenants across servers? Horizontal scaling.
- The complete key-by-key reference? Configuration.