Courses

Filament 3 From Scratch: Practical Course

Multi-Tenancy in Filament 3

Summary of this lesson:
- Setting up multi-tenant applications
- Managing tenant relationships
- Implementing tenant scopes
- Handling tenant switching

Filament 3 comes with multi-tenancy support out of the box: the screenshot below shows how you can switch between teams/companies, see on the top-left:

This lets you quickly set up a multi-tenant application within a single database, just by configuring the panel. It even takes care of the switching between tenants for you.


Disclaimer: Tenancy is Hard.

It is important to note here that the meaning of multi-tenancy is different for everyone and that the demo in this lesson is just one of the possible implementations. It is not a one-size-fits-all solution. And the tenancy implementation also depends on your custom code more than on Filament core functionality.

Filament documentation says this:

Filament does not provide any guarantees about the security of your application. It is your responsibility to ensure that your application is secure. Please see the security section for more information.

With that said, here's our approach:

  • Configure your tenant Model. For example, Company, Organization, Team, etc.
  • Each User needs to have a belongsToMany relationship with that Tenant model. In other words, user may belong to many teams.
  • Apply the tenant to your PanelProvider to indicate that this panel is multi-tenant.
  • All of your Models must contain a tenant_id column, or an alternative, like company_id, organization_id, team_id, etc.
  • You must apply global scopes to all your Models to filter the data by the current tenant. Filament handles some of this, but that makes you prone to errors. It is better to do it yourself.
  • There is no multi-database support. All of your tenants will have to be in the same database. Switching between them is done by filtering the data by the current tenant, and each tenant is identified by its ID in the URL segment.

Telling Filament that Your Panel is Multi-Tenant

First, we have to create a multi-tenancy model, which in our case will be Company:

Migration

Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
 
Schema::create('company_user', function (Blueprint $table) {
$table->foreignId('company_id')->constrained();
$table->foreignId('user_id')->constrained();
});

app/Models/Company.php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 
class Company extends Model
{
protected $fillable = [
'name'
];
 
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
}

Once we have our Company model, we can tell Filament that our panel is multi-tenant by adding the tenant() method to our PanelProvider:

app/Providers/Filament/AdminPanelProvider.php

use App\Models\Company;
 
// ...
 
public function panel(Panel $panel): Panel
{
return $panel
->default()
->tenant(Company::class)
// ...
}

This informs Filament that it should use the Company model as the multi-tenancy model for this panel. But if you try to access your panel now, you will get an error:

This is because we still need to update our User model. We need to implement Filament\Models\Contracts\HasTenants and add the canAccessTenant() method:

app/Models/User.php

use Filament\Models\Contracts\FilamentUser;
use Filament\Models\Contracts\HasTenants;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Collection;
use Laravel\Sanctum\HasApiTokens;
 
class User extends Authenticatable implements FilamentUser
class User extends Authenticatable implements FilamentUser, HasTenants
{
use HasApiTokens, HasFactory, Notifiable;
 
// ...
 
public function canAccessPanel(Panel $panel): bool
{
return $this->is_admin == 1;
}
 
public function companies(): BelongsToMany
{
return $this->belongsToMany(Company::class);
}
 
public function canAccessTenant(Model $tenant): bool
{
return $this->companies->contains($tenant);
}
 
public function getTenants(Panel $panel): array|Collection
{
return $this->companies;
}
}

Once we have this in place, we can access our panel again:

That's it. Our panel is now informed that it is a multi-tenant application. But there's still a bit of work to do.


Making Your Models Multi-Tenant

As you might have guessed by now, your models must also support multi-tenancy. Otherwise, if you try to load a resource that doesn't support it, you will get an error:

Note: The following actions have to be done for all of your models.

Filament assumes that you have a company() relationship method on your Model. So let's add it:

Migration

Schema::table('products', function (Blueprint $table) {
$table->foreignId('company_id')->constrained();
});

app/Models/Product.php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
// ...
 
class Product extends Model
{
// ...
 
public function company(): BelongsTo
{
return $this->belongsTo(Company::class);
}
}

Now we can load our resource again:

We can even see that the query is filtered by the current tenant, but we haven't added anything to our Product model yet:

This is Filament trying to be helpful and apply a global scope to your model. And while it's a nice gesture, it allows us to accidentally load data from other tenants using a custom query.


Implementing Global Scopes

To prevent any accidental data leaks, Filament recommends us to implement a global scope Middleware on our models:

To do that, we have to create a new Middleware:

php artisan make:middleware ApplyTenantScopes

Inside this Middleware, we will apply the global scope to all of our models:

app/Http/Middleware/ApplyTenantScopes.php

 
use App\Models\Category;
use App\Models\Order;
use App\Models\Product;
use App\Models\Tag;
use Filament\Facades\Filament;
 
use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
 
// ...
 
class ApplyTenantScopes
{
public function handle(Request $request, Closure $next): Response
{
// Can also be moved to each model.
// This is to prevent data leaking when doing dashboard reports
// and other more complicated queries that touch databases
Category::addGlobalScope(
fn(Builder $query) => $query->whereBelongsTo(Filament::getTenant()),
);
Order::addGlobalScope(
fn(Builder $query) => $query->whereBelongsTo(Filament::getTenant()),
);
Tag::addGlobalScope(
fn(Builder $query) => $query->whereBelongsTo(Filament::getTenant()),
);
Product::addGlobalScope(
fn(Builder $query) => $query->whereBelongsTo(Filament::getTenant()),
);
 
return $next($request);
}
}

And then we can register it in our AdminPanelProvider:

app/Providers/Filament/AdminPanelProvider.php

use App\Http\Middleware\ApplyTenantScopes;
// ...
 
class AdminPanelProvider extends PanelProvider
{
public function panel(Panel $panel): Panel
{
return $panel
->default()
->tenant(Company::class)
->tenantMiddleware([
ApplyTenantScopes::class,
], isPersistent: true)
// ...
}
}

Once that is done, the current tenant will filter our models even if we try to load them with a custom query.


How to Switch Between Tenants

When everything is configured, and your multi-tenant user is logged in, you will be able to switch between tenants by using the dropdown above the sidebar:

Switching it will switch the current tenant, and all the data will be filtered by the new tenant in the URL segment. For example, we will look at Apple products:

And our query will be filtered by the new tenant:

select `categories`.`name`, `categories`.`id`
from `categories`
where `categories`.`company_id` in (2)
order by `categories`.`name` asc

But if we switch to Google, we will see that the new tenant filters the data:

And our query will be filtered by the new tenant:

select `categories`.`name`, `categories`.`id`
from `categories`
where `categories`.`company_id` in (1)
order by `categories`.`name` asc
Previous: Restrict Add/Edit/Delete Actions and Buttons
avatar

Povilas, I'm creating a document manager SAAS for accountants. In it I will have some Global Templates that will serve to classify the records, which must be accessed by all Tenants (Document Types, Categories) but which cannot be edited by Tenants. These are tables that can only be edited by an Admin and must not be filtered by a global scope. Can you point me to documentation that helps me achieve this?

avatar

Maybe the section about Disabling global scopes?

avatar

Thanks! I'll check this.

avatar

I have the same problem, I try to setup multi tenancy but I have some tables that are for general usage and shouldnt be scoped. Or i want (same as with claudio) that admins can view everything.

I tried adding this to the ModelResource.php:

public static function getEloquentQuery(): Builder
    {
       return parent::getEloquentQuery()->withoutGlobalScopes([Company::class]);
   }

or this:

 protected static ?string $tenantOwnershipRelationshipName = null;
 

I tried using a ApplyTenantScopes and then using something like this:

 Model::withoutGlobalScope(Company::class);

But nothing seems to work. I saw in your older documentation about Filament 2.0 a possible solution (//post/multi-tenancy-laravel-filament-simple) but I don't know what a good soluton for 3.0 would be.

avatar

To be perfectly honest, the way how Filament v3 Multi-Tenancy is done, personally to me, seems not perfect at the moment, so I don't have a quick answer. But will try to debug and comment with possible solutions a bit later.

avatar

Ok so with the help of Dan Harrin and the filament github codebase I found a solution, copy paste the following code in the Resource that you want to exclude from the tenant scope:

public static function scopeEloquentQueryToTenant(Builder $query, ?Model $tenant): Builder
    {
        return $query;
    }

And include in the top of the same file:

use Illuminate\Database\Eloquent\Model;

You basicly override the tenantscope function and return it cleanly. I haven't found problems yet, so I think (hope) this works as intended. :)

avatar

To remove the scopes from your Resource, you can do this:

CategoryResource -> Create new method:

public static function getEloquentQuery(): Builder
{
		return static::getModel()::query()->withoutGlobalScopes();
}

This will override the Query creation from Filament and return you a new instance without Tenant information. Will that work everywhere? Not sure... Filament multi-tenancy does not really support:

  • Global resources for everyone
  • Admin roles

It is more or less designed for independant tenants to live within your application and never interact.

ps. You can technically create an admin by creatin a new panel that doesn't have tenancy applied to it. It duplicates the resources and everything else but... It should work :)

avatar
You can use Markdown
avatar

Thanks, Povilas. Gang, I agree that Tenancy is hard! I had a minor problem figuring out which of the many "Builder" classes to import into ApplyTenantScopes and :

use Illuminate\Contracts\Database\Eloquent\Builder;

seemed to work best for me after trial and error. Maybe this will help some other newbie!

👍 1
avatar

Thanks, sorry for the confusion! Now added three missing import classes to the lesson, it wasn't only Builder, the correct import from the docs:

use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
avatar
You can use Markdown
avatar

To be able to share a record between several teams, it would be possible to use a Pivot Table?

avatar

I don't think that currently it's possible in Filament, at least I haven't seen it in the documentation.

avatar
You can use Markdown
avatar

Hi Povilas,

I tried to replicate tenancy at this project, and so far so good....but when I need to add a product, I get the error that General error: 1364 Field 'company_id' doesn't have a default value, what is missing to me?

Thank You!

avatar

I've discover the problem and now its working :) I found a video of you at youtube :) "Simple Multi-Tenancy in Filament: TWO Ways" Thank You!

avatar

Great article .

avatar
You can use Markdown
avatar

Alright, so with multi tenacy, there is also an option where users or other models would only be able to see their own data. Thus the "swtiching" would be unnecessary. Is the process the same for this requirement?

For example if i make a user panel, which allows users to update and manage content and settings related to them? Or a group panel. Think social media usage primarily. But may be good for courses, stores or other use cases.

This is a big topic that I hope you might have or be willing to make a tutorial for. Also considering larger tables that you may want to split into several pages instead of tabs. Can you have multiple resource pages all using the same table but handling different fields? Example if my user table has a group of fields for login data, then another group for demographic data, or special interests. or whatever that may fit within a single table.

avatar
You can use Markdown
avatar

Hi there,

I'm implementing a solution where we need 1 user per tenant, and not a user can belong to many tenants. Is there an example I can look at?

avatar

Some of our other articles might help you:

//tag/multi-tenancy?source=search

In general, it's as simple as adding the tenant_id and it's scopes :)

avatar
You can use Markdown
avatar

Can you please share full code repository? I was unable to implement tenatcy. So, it would be helpful to me as well as others.

Thanks

avatar

In the last lesson you can see the repository: https://github.com/LaravelDaily/Filament3-Course-Main

avatar

I look at your repo but could not find any code related to Tenant. For example, I did not find Company resource, Updated User Model that are responsible for Tenant.

Can you please check again and give me updated link!

Or can you please give me a screenshot?

Thanks.

avatar

Have you switched the branch? :)

There's quite a few of them there, but this one should have the tenancy implementation:

https://github.com/LaravelDaily/Filament3-Course-Main/tree/feature/multi-tenancy

avatar
You can use Markdown
avatar
You can use Markdown