Skip to main content

Tenancy

FilamentFlow supports multi-tenancy out of the box. You can enable tenancy by setting the tenancy.enabled key in the filament-flow.php configuration file to true.

config/filament-flow.php
'multi_tenancy' => [
'enabled' => env( 'TENANCY_ENABLED', true ),
],

This is configured according to the Filament Tenancy documentation, and supports all the other features of FilamentFlow.

Panel Support

The multi-tenancy feature is only added to the AppPanelProvider.php file in the default configuration. If you are using a custom panel, you will need to add the tenancy middleware to your panel routes as shown below.

Adding Tenancy to a Custom Panel

YourNewPanelProvider.php
use App\Traits\PanelProviderTrait;
class YourNewPanelProvider extends PanelProvider
{
use PanelProviderTrait;

/**
* @throws \Exception
*/
public function panel(Panel $panel): Panel
{
return $this->getPanelBase(
panel: $panel,
id: 'your_new_panel',
useTenancy: true
)
->path('your-new-panel')
... // other panel configuration
}
}

Tenant Security

When using tenancy, you should ensure that you are extending the TenantAwareBaseModel model on your models (rather than extends Model) to ensure that the tenant is properly set on the model.

Automatic Model Creation

This has been automatically added to an override for the php artisan make:model command, but feel free to adjust it by either removing or editing the stub file in the stubs directory.

The TenantAwareBaseModel model is a custom model that extends the Model class and adds a team_id global scope to the model. This field is automatically set to the current tenant when the model is created.

Additionally, the php artisan make:migration command uses the stubs/migration.create.stub file to add the team_id field to the migration file. This field is automatically set to the current tenant when the model is created.

app/Models/YourModel.php
use App\Models\TenantAwareBaseModel;

class YourModel extends TenantAwareBaseModel
{
...
}

Use of the Team ID

For simplicity, the team_id field is used as the tenant identifier. This field is automatically set to the current tenant when the model is created. You can adjust this field to match your application's needs.

# In a controller or the boot method of a service provider
$query->where('team_id', auth()->user()->team_id);

# In a migration file
$table->foreignId('team_id')->constrained()->onDelete('cascade');

Tenancy Helper Methods

The app/Support/helpers.php file provides basic helper methods for working with tenancy in your application. You can use these methods in your controllers, views, and other parts of your application, and they are particularly useful for working with the FilamentFlow multi-tenancy feature and navigation routes.

app/Support/helpers.php
function get_current_tenant(): ?Model
{
if( auth()->check() && Filament::hasTenancy() )
{
return auth()->user()->getDefaultTenant( app( Panel::class ) );
}
return null;
}