Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
Step-by-step Filament v5 multi-tenancy: teams, tenant registration, automatic scoping, scopedUnique validation, subdomains, queued jobs and a tenant security checklist.
Key takeaways
team_id, and the panel scopes queries to the current team automatically.->tenant(Team::class) on the panel, the HasTenants interface on User, and a team() relationship on each tenant-owned model.unique and exists rules ignore tenant scopes. Use scopedUnique() and scopedExists() instead.Also Read: Filament on Laravel 13: The Complete Compatibility Checklist
Most SaaS products end up needing the same thing: a panel where each customer (a “team”, “workspace” or “organisation”) sees only its own data, can invite colleagues and has its own billing. Filament v5 has this built in, and since v4 it’s much safer by default, because Filament now scopes all queries in a tenant panel instead of just resource tables.
We’ll build a multi-tenant “app” panel for a simple CRM, with teams, members and a Customer resource.
| Approach | How it works | Filament fit |
|---|---|---|
Single database, team_id column | Every row belongs to a tenant | Native. This is what ->tenant() does |
| Database per tenant | Switch connection per request | Possible with packages like stancl/tenancy, but outside Filament’s tenancy feature |
| Separate app per customer | One deployment each | No tenancy needed. High ops cost |
Filament’s docs are clear that tenancy here means “a single instance of the application serves multiple customers” with shared tables. It’s the right choice for most B2B SaaS products up to very large scale. If compliance requires physically separate databases, look at a database-per-tenant package instead.
php artisan make:model Team -m
php artisan make:migration create_team_user_table
php artisan make:model Customer -m// create_teams_table
Schema::create('teams', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
// create_team_user_table
Schema::create('team_user', function (Blueprint $table) {
$table->foreignId('team_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('role')->default('member');
$table->primary(['team_id', 'user_id']);
});
// create_customers_table
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->foreignId('team_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->string('email');
$table->timestamps();
$table->unique(['team_id', 'email']); // unique per tenant, not globally
$table->index(['team_id', 'created_at']);
});Two details here save pain later: composite unique indexes that include team_id, and composite indexes that start with team_id, because every tenant query filters on it first.
// app/Models/Team.php
class Team extends Model
{
protected $fillable = ['name', 'slug'];
public function members(): BelongsToMany
{
return $this->belongsToMany(User::class)->withPivot('role');
}
public function customers(): HasMany
{
return $this->hasMany(Customer::class);
}
}
// app/Models/Customer.php
class Customer extends Model
{
protected $fillable = ['name', 'email'];
public function team(): BelongsTo
{
return $this->belongsTo(Team::class);
}
}By convention, Filament looks for a relationship named after the tenant model (team) on each resource’s model, and for a plural relationship on the tenant (customers) for the resource.
// app/Models/User.php
use Filament\Models\Contracts\FilamentUser;
use Filament\Models\Contracts\HasDefaultTenant;
use Filament\Models\Contracts\HasTenants;
use Filament\Panel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
class User extends Authenticatable implements FilamentUser, HasTenants, HasDefaultTenant
{
public function teams(): BelongsToMany
{
return $this->belongsToMany(Team::class)->withPivot('role');
}
public function canAccessPanel(Panel $panel): bool
{
return $this->hasVerifiedEmail();
}
public function getTenants(Panel $panel): Collection
{
return $this->teams;
}
public function canAccessTenant(Model $tenant): bool
{
return $this->teams()->whereKey($tenant)->exists();
}
public function getDefaultTenant(Panel $panel): ?Model
{
return $this->teams()->latest('team_user.team_id')->first();
}
}canAccessTenant() is your main security check. Filament calls it to stop a user from changing /app/acme in the URL to someone else’s team.
// app/Providers/Filament/AppPanelProvider.php
use App\Filament\Pages\Tenancy\EditTeamProfile;
use App\Filament\Pages\Tenancy\RegisterTeam;
use App\Models\Team;
public function panel(Panel $panel): Panel
{
return $panel
->id('app')
->path('app')
->login()
->registration()
->tenant(Team::class, slugAttribute: 'slug')
->tenantRegistration(RegisterTeam::class)
->tenantProfile(EditTeamProfile::class)
->searchableTenantMenu()
// ...
;
}URLs now look like /app/acme/customers. If you prefer subdomains, use ->tenantDomain('{tenant:slug}.example.com'), and read the domain-routing note in our Laravel 13 compatibility checklist first.
// app/Filament/Pages/Tenancy/RegisterTeam.php
namespace App\Filament\Pages\Tenancy;
use App\Models\Team;
use Filament\Forms\Components\TextInput;
use Filament\Pages\Tenancy\RegisterTenant;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Illuminate\Support\Str;
class RegisterTeam extends RegisterTenant
{
public static function getLabel(): string
{
return 'Create a team';
}
public function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')
->required()
->maxLength(100)
->live(onBlur: true)
->afterStateUpdated(fn (Set $set, ?string $state) => $set('slug', Str::slug($state))),
TextInput::make('slug')
->required()
->alphaDash()
->unique(Team::class, 'slug'),
]);
}
protected function handleRegistration(array $data): Team
{
$team = Team::create($data);
$team->members()->attach(auth()->user(), ['role' => 'owner']);
return $team;
}
}EditTeamProfile extends Filament\Pages\Tenancy\EditTenantProfile and has the same shape: a getLabel() and a form(). Restrict who can edit it with canView(Model $tenant), for example owners only.
php artisan make:filament-resource Customer --generateWith no extra code, the Customer resource:
/app/acme/customers/15/edit only if customer 15 belongs to Acme,team_id automatically when a customer is created, andSince v4, Filament applies tenant scoping to all queries made in the panel, using global scopes, and associates new records with the tenant through model events. In v3, only resource queries were scoped.
If your relationship names don’t follow the convention, set them explicitly:
protected static ?string $tenantOwnershipRelationshipName = 'organisation';
protected static ?string $tenantRelationshipName = 'clients';For resources that are genuinely global inside a tenant panel (a shared Country list, for example), opt out:
protected static bool $isScopedToTenant = false;This is the most common tenancy bug in Filament apps. Laravel’s unique and exists rules run their own queries, without Eloquent global scopes. A plain ->unique() on a customer’s email checks every team’s customers, so two companies can’t both have [email protected] as a customer, and the error message leaks that the email exists somewhere else.
Use the scoped variants:
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
TextInput::make('email')
->email()
->required()
->scopedUnique(), // unique within the current team
Select::make('account_manager_id')
->relationship('accountManager', 'name')
->scopedExists(), // must exist within the current team's scopeThe same applies to Select::relationship() options for models the panel doesn’t scope. Check that every dropdown only lists the current team’s records.
Tenant scoping comes from the panel’s request lifecycle. These don’t go through it:
$team->customers()), or re-apply a scope yourself.team_id from the import’s options or the user, and validate against it (see our CSV import/export guide).class RecalculateCustomerScores implements ShouldQueue
{
use Queueable;
public function __construct(public Team $team) {}
public function handle(): void
{
$this->team->customers()->lazyById()->each->recalculateScore();
}
}To apply global scopes to other models in panel requests too, register tenant middleware that is persistent across Livewire requests:
->tenantMiddleware([
\App\Http\Middleware\ApplyTenantScopes::class,
], isPersistent: true)The role pivot column is enough for owner/admin/member rules in policies:
public function delete(User $user, Customer $customer): bool
{
$role = $user->teams()->whereKey($customer->team_id)->first()?->pivot->role;
return in_array($role, ['owner', 'admin'], true);
}For granular permissions per team, combine spatie/laravel-permission’s teams mode with Filament Shield’s tenancy support. We cover that in roles and permissions in Filament.
Filament ships a billing hook: ->tenantBillingProvider(...) plus ->requiresTenantSubscription(). You can use Laravel Spark’s provider, or write your own with Laravel Cashier. Our Filament + Stripe subscription guide builds the Cashier version step by step.
use Filament\Facades\Filament;
use function Pest\Livewire\livewire;
it('never shows another team\'s customers', function () {
[$acme, $globex] = Team::factory()->count(2)->create();
$user = User::factory()->create();
$user->teams()->attach($acme);
$mine = Customer::factory()->for($acme)->count(3)->create();
$theirs = Customer::factory()->for($globex)->count(3)->create();
$this->actingAs($user);
Filament::setCurrentPanel('app');
Filament::setTenant($acme);
Filament::bootCurrentPanel();
livewire(ListCustomers::class)
->assertCanSeeTableRecords($mine)
->assertCanNotSeeTableRecords($theirs);
});Filament::bootCurrentPanel() applies the tenant scopes and model listeners in tests, as described in the testing docs. More patterns are in testing Filament panels with Pest.
canAccessTenant() checks membership, not just “logged in”.team_id, a foreign key and composite indexes.scopedUnique() / scopedExists() replace unique() / exists() on tenant data.->directory(fn () => 'teams/'.Filament::getTenant()->id)).Yes. Filament has built-in single-database tenancy with ->tenant(), tenant registration and profile pages, a tenant switcher, automatic query scoping and billing hooks.
Not natively. Filament’s tenancy is row-based. For a separate database per tenant, use a package such as stancl/tenancy alongside a panel that isn’t Filament-tenant-aware.
Laravel’s unique rule bypasses Eloquent global scopes, so it checks all tenants. Use Filament’s scopedUnique() and a composite unique index on (team_id, column).
Call Filament\Facades\Filament::getTenant() inside panel requests. In jobs and commands there’s no current tenant, so pass it in yourself.
Related on The Web Tier: Filament + Stripe subscription billing · Roles and permissions in Filament