# Multi-tenancy in Filament: single database, database-per-tenant, or both

> Filament multi-tenancy compared, with examples: built-in single database tenancy, a database per tenant with stancl/tenancy, or both in one app.

You are adding workspaces to a Filament panel: every customer gets a team, and nobody may ever see another team's projects. The first decision is where each team's rows live. They can all sit in one database and be told apart by a `team_id` column, or each team can get a database of its own. Some apps do both.

This guide sets out the three options for a Filament v5 panel, with an example of each: how it works, which package does it well, and the questions that decide between them. The short version comes first.

## The short answer

| | Single database | Database per tenant | Both (hybrid) |
| --- | --- | --- | --- |
| How rows are separated | a `team_id` column and a query scope | the request runs on the tenant's own database connection | per tenant: scope for some, own database for others |
| Who does it | Filament's built-in tenancy (`->tenant()` on the panel) | stancl/tenancy, or spatie/laravel-multitenancy | stancl/tenancy plus your own routing, or a package built for it |
| A new signup costs | one row | creating and migrating a database (usually queued) | one row, or a database for the tenants that get one |
| Migrations | once | once per tenant database | once, plus once per private database |
| Per-tenant backup, export, delete | queries by `team_id` | dump or drop one database | depends on the tenant |
| What to watch | every query outside the panel carries its tenant constraint | deploy time and connections grow with the tenant count | the shared and private schemas stay identical |
| Great for | most SaaS apps, B2C, free tiers, thousands of small teams | B2B customers who ask where their data lives, compliance, data residency | pricing tiers that map to isolation |

If you are starting out and none of your customers has asked about their data's location, Filament's built-in tenancy is the place to start. Everything below explains why, and what changes the answer.

```mermaid
flowchart LR
    req("Request\n/app/acme/projects")
    panel("Filament panel\ncurrent tenant: acme")
    subgraph single ["Single database"]
        direction TB
        scope("Global scope\nwhere team_id = acme")
        db1[("app database\nevery team's rows")]
    end
    subgraph multi ["Database per tenant"]
        direction TB
        switch("Connection switch\nby a tenancy bootstrapper")
        db2[("tenant_acme\nacme's rows only")]
    end
    req --> panel
    panel --> scope
    scope --> db1
    panel --> switch
    switch --> db2
```

## Single database: Filament's built-in tenancy

Filament ships multi-tenancy in the panel itself. One method turns a panel into a tenant panel:

```php
// app/Providers/Filament/AppPanelProvider.php
use App\Models\Team;
use Filament\Panel;

public function panel(Panel $panel): Panel
{
    return $panel
        ->id('app')
        ->path('app')
        ->tenant(Team::class);
}
```

Your `User` model implements `Filament\Models\Contracts\HasTenants`, which asks for two methods: `getTenants()` for the teams a user can switch between and `canAccessTenant()` to check membership.

Each model that belongs to a team has a `team()` relationship. Filament derives that name from the tenant model's class, and `->tenant(Team::class, ownershipRelationship: 'workspace')` changes it.

```php
use Filament\Models\Contracts\HasTenants;
use Filament\Panel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Collection;

class User extends Authenticatable implements HasTenants
{
    public function teams(): BelongsToMany
    {
        return $this->belongsToMany(Team::class);
    }

    public function getTenants(Panel $panel): Collection
    {
        return $this->teams;
    }

    public function canAccessTenant(Model $tenant): bool
    {
        return $this->teams()->whereKey($tenant)->exists();
    }
}
```

From there Filament does the scoping for you. For each model with a resource in the panel, it adds a global scope once the tenant is identified, so the model's Eloquent queries carry `where team_id = ?` (through `whereBelongsTo()` for a `BelongsTo` relationship). When a record is created in the panel, Filament associates it with the current team.

The tenant appears in the URL (`/app/acme/projects`), or on a subdomain or a whole domain with `tenantDomain()`. A registration page lets users create a team, a profile page lets them edit it, and a billing integration with Laravel Spark is available as `filament/spark-billing-provider`.

What stays yours is everything outside that scope, and the [Filament tenancy docs](https://filamentphp.com/docs/5.x/users/tenancy) set out where it ends:

- Queries made outside the tenant-aware panel, or before the tenant is identified, need their own tenant constraint. In most apps that means your jobs, commands and reports.
- Models without a resource in the panel get no scope; you add one yourself.
- The query builder (`DB::table()`) does not apply model global scopes.
- Laravel's `unique` and `exists` rules don't go through the model, so Filament offers `scopedUnique()` and `scopedExists()` for form fields.
- Tenant scoping is not record authorization, so policies still matter.

Two packages fill in the rest of a team-based app on top of this. [Filament Shield](https://github.com/bezhanSalleh/filament-shield) supports tenancy (`shield:setup --tenant=...`), with roles kept per team through Spatie Permission's teams feature. [Filament Teams](https://packstub.dev/plugins/filament-teams), a free MIT package of ours, adds a Members page, email and link invitations, seat limits and roles per team, and works with Filament's built-in tenancy and with Shield's roles ([setup](https://packstub.dev/docs/filament-teams/shield)).

**Choose the single database when** your tenants are many and mostly small, signups should be instant, you want one migration run per deploy, and your team is comfortable keeping every raw query scoped. A single database also scales a long way with good indexes: [Fast Filament v5 tables for large, tenant-scoped data](https://packstub.dev/guides/filament-table-performance-large-tenant-data) walks through one team with 400,000 orders.

## Database per tenant: stancl/tenancy

[stancl/tenancy](https://tenancyforlaravel.com) (Tenancy for Laravel) supports both models and focuses on multi-database tenancy: giving each tenant its own database. For single-database setups, it ships a `BelongsToTenant` trait that scopes models by tenant.

For a database per tenant, stancl/tenancy identifies the tenant from the domain, subdomain, path or request data, then runs **bootstrappers** that make Laravel tenant-aware for the rest of the request. In the current stable release, they include:

- `DatabaseTenancyBootstrapper`, which switches the default connection to the tenant's database,
- `CacheTenancyBootstrapper`, which tags cache entries per tenant,
- `FilesystemTenancyBootstrapper`, which gives each tenant its own storage paths,
- `QueueTenancyBootstrapper`, which carries the tenant into queued jobs,
- a Redis bootstrapper that prefixes keys per tenant.

Your models then need no `team_id` and no scope. While a request runs for Acme, `Project::all()` returns Acme's projects because the connection *is* Acme's database. Once the tenant is initialized, for a request or a queued job, a report written in raw SQL or a forgotten `where` stays inside that tenant's database. Backing up, exporting, restoring or deleting a tenant is one database. A large tenant can sit on a server of its own, close to where its data has to live.

The upcoming [v4](https://v4.tenancyforlaravel.com/version-4) adds more bootstrappers and an experimental PostgreSQL Row-Level Security option for single-database setups.

[spatie/laravel-multitenancy](https://spatie.be/docs/laravel-multitenancy/v4/introduction) takes a deliberately small approach: it determines the current tenant and runs the **tasks** you choose when a tenant becomes current, such as switching the database or prefixing the cache. It works with one database or many, and suits teams who prefer to wire each piece themselves.

A database per tenant asks for a few decisions up front, whichever package you pick:

- **Signup takes a moment.** Creating and migrating a database is work for a queue, so the user waits on a short "setting up your workspace" step instead of landing in the panel at once.
- **Migrations run per tenant.** stancl's `tenants:migrate` runs the tenant migrations against every tenant database, so it becomes a step of each deploy.
- **Users usually stay central.** Logging in once and switching between workspaces works best with `users` and `sessions` in a central database and tenant data elsewhere. If every tenant should be its own login realm, with separate credentials on each tenant's host, that is the model stancl is designed around, and plain stancl with Filament is the right fit.
- **Foreign keys stop at the database.** A `posts.user_id` cannot be a constraint into a `users` table in another database; it becomes a plain column, or the users a tenant needs are copied into its database.
- **Files follow the tenant too.** Once a tenant is initialized, stancl's filesystem bootstrapper moves every disk listed in `tenancy.filesystem.disks` (`local` and `public` by default) into that tenant's own folder, or its own prefix in the bucket. Code that runs without a tenant, such as a central route or an endpoint that skips tenancy, still uses the shared root. So a file saved by that code and opened later in a tenant request is looked for in the tenant's folder, where it isn't. When a file is saved outside tenancy and read inside it (or the other way round), put it on a disk of its own and leave that disk off the list.

**Choose a database per tenant when** your tenants are businesses that ask where their data lives, per-tenant backup and restore matters, or you want isolation that does not depend on every query being scoped. As a rough guide rather than a measured limit, tens to thousands of tenants is a comfortable range for this model; past that, many small tenants usually sit better as rows.

## Both: shared by default, private when a customer needs it

The two models compose. The pattern looks like this: most tenants share a database and are told apart by a `tenant_id` column (the `team_id` of the single-database section), and the tenants that need it (an enterprise plan, a regulated customer) get a database of their own, possibly on their own server.

```mermaid
flowchart LR
    req("Request\n/app/acme/projects")
    panel("Filament panel\ncurrent tenant: acme")
    check{"acme's\nisolation mode?"}
    scope("Global scope\nwhere tenant_id = acme")
    switch("Connection switch\nto tenant_acme")
    central[("Shared database\nfree and standard tiers")]
    private[("tenant_acme\nown database, any server")]
    req --> panel --> check
    check -- "shared" --> scope --> central
    check -- "dedicated" --> switch --> private
```

Whatever tooling you use, a hybrid needs two things:

1. **A per-tenant switch.** Each request decides whether to scope by `tenant_id` or switch the connection, based on a flag stored on the tenant. In stancl/tenancy v4 that can be the choice of bootstrappers for that tenant.
2. **A schema that is ready to move.** Design the shared tables as if every tenant already lived in its own database: put `tenant_id` on every table of tenant data, pivots included, and keep foreign keys between a tenant's rows and central rows as plain indexed columns rather than constraints.

   ```php
   Schema::create('projects', function (Blueprint $table) {
       $table->id();
       // Plain indexed columns, not ->constrained(): tenants and users
       // stay central when this table moves to a private database.
       $table->unsignedBigInteger('tenant_id')->index();
       $table->unsignedBigInteger('owner_id')->index();
       $table->string('name');
       $table->timestamps();
   });
   ```

   Foreign keys between two tables of tenant data, such as `tasks.project_id`, can stay real constraints, since both tables move together. Then moving a customer from the shared database to a private one is a copy of their rows, not a schema change, and the `tenant_id` column does no harm in a database that holds a single tenant.

**Choose both when** your pricing tiers map to isolation: a free or self-serve tier that should sign up instantly, and a higher plan whose customers want their own database.

## Questions that settle it

- **Who are your tenants?** Individuals and small teams lean towards a single database; companies with security questionnaires lean towards their own database.
- **How many will you have?** As a rule of thumb, thousands of mostly small tenants are easiest as rows, and tens to thousands of paying businesses sit comfortably in databases of their own.
- **Has anyone asked where their data lives, or for a copy of all of it?** One yes is a reason to support a private database for that customer, which is the hybrid.
- **One login, or one login per tenant?** A workspace picker after a single sign-in keeps users central. A separate sign-in per tenant host points to stancl/tenancy on its own terms.
- **Who runs it?** A database per tenant means more databases to migrate, back up and watch. A queue worker and a deploy step that runs tenant migrations are part of the setup.

## When to keep it simple

If you have one panel, a handful of customers and no data-location requirements, stay with Filament's built-in tenancy. It is a few lines of code, it is documented and maintained with Filament itself, and the `team_id` columns you add now are exactly what a later move to a hybrid needs. You can add a database per tenant for the customers who ask, when they ask.

## One way to run both in a Filament v5 panel

[Filament Tenancy](https://packstub.dev/plugins/filament-tenancy) is our Pro plugin for this: database-per-tenant for Filament v5 panels, built on stancl/tenancy v4.

One config key, `database_strategy`, sets the app-wide model to `dedicated` (a database per tenant, the default) or `shared` (`tenant_id` scoping, applied through Filament's own resource scoping, with an optional PostgreSQL Row-Level Security layer from stancl v4). Each tenant can override it at creation with an `isolation_mode` attribute, which is the hybrid above. `php artisan tenants:move` moves a tenant's rows between the shared database, shard databases and a private database.

An app that already runs Filament's built-in tenancy keeps its `Team` model, its ids and its `team_id` columns. `php artisan tenancy:adopt "App\Models\Team"` makes every existing team a tenant on the shared strategy, ready to give one of them a database later.

The plugin installs with `composer require packstub/filament-tenancy` from Packstub's Composer repository. Because stancl/tenancy v4 has no tagged release yet, the registry serves a tested v4 snapshot as a stable version and Composer needs no stability changes ([details](https://packstub.dev/docs/filament-tenancy/installation#stancltenancy-v4-stability)). [Filament Teams](https://packstub.dev/docs/filament-teams/filament-tenancy) works with it for members and invitations.

The [database strategies](https://packstub.dev/docs/filament-tenancy/database-strategies) page covers both models in depth, including a comparison table, sharding and moving a tenant between modes. Read it next if a hybrid is where your app is heading.
