PHPackages                             angelitosystems/filament-tenancy - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. angelitosystems/filament-tenancy

ActiveLibrary[Database &amp; ORM](/categories/database)

angelitosystems/filament-tenancy
================================

Tenancy package for Filament - multi-database tenants + central support

v1.0.4(7mo ago)920[1 issues](https://github.com/angelitosystems/filament-tenancy/issues)MITPHPPHP ^8.1|^8.2|^8.3

Since Nov 2Pushed 7mo agoCompare

[ Source](https://github.com/angelitosystems/filament-tenancy)[ Packagist](https://packagist.org/packages/angelitosystems/filament-tenancy)[ Docs](https://github.com/angelitosystems/filament-tenancy)[ RSS](/packages/angelitosystems-filament-tenancy/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (7)Versions (6)Used By (0)

Filament Tenancy
================

[](#filament-tenancy)

A comprehensive multi-tenancy package for Filament with support for multiple databases, central management, advanced logging, and performance monitoring.

Features
--------

[](#features)

- **🚀 Easy Installation** - Interactive installer with automatic setup
- **👥 User Management** - Create and manage tenant users with roles and permissions
- **🔐 Roles &amp; Permissions** - Complete Spatie-like RBAC system for tenant access control
- **📦 Asset Sharing** - Share Livewire, Filament, and custom assets from central to tenants
- **👥 Admin User Creation** - Interactive admin user creation during installation
- **🗄️ Multi-database tenancy** - Complete isolation between tenants
- **🎛️ Central tenant management** - Unified control panel for all tenants
- **⚡ Automatic database creation and migration** - Seamless tenant provisioning
- **🔄 Tenant-aware middleware** - Automatic context switching
- **🎨 Filament integration** - Native Filament admin panel support
- **🔐 Secure credential management** - Encrypted credential storage with rotation
- **📊 Enhanced Debug Logging** - Environment-aware logging with production-safe output
- **📈 Performance monitoring** - Real-time metrics and connection monitoring
- **🔌 Connection pooling** - Optimized database connection management
- **💳 Plans &amp; Subscriptions** - Built-in plan and subscription management
- **💳 PayPal Integration** - Complete PayPal payment integration with webhooks support
- **🛡️ Database compatibility check** - Automatic validation of database requirements
- **🧹 Smart error handling** - Automatic retry and cleanup on connection errors
- **🌐 APP\_DOMAIN Auto-Detection** - Automatic domain detection from APP\_URL for subdomain tenancy
- **🔧 Enhanced Tenant Creation** - Interactive wizard with automatic domain configuration
- **🎨 Custom 404 Page** - Beautiful personalized 404 page for tenant not found errors with Livewire component support
- **⚖️ License-Based** - Future licensing model for commercial use (currently public access)

Installation
------------

[](#installation)

### Quick Install

[](#quick-install)

The easiest way to install Filament Tenancy is using the interactive installer:

```
composer require angelitosystems/filament-tenancy
php artisan filament-tenancy:install
```

The installer will:

- ✅ Check if Filament is installed and install it if needed
- ✅ Verify database compatibility (MySQL/PostgreSQL required)
- ✅ Configure database connection interactively if needed
- ✅ Publish configuration files
- ✅ Run migrations automatically
- ✅ **Create default plans automatically** (Basic, Premium, Enterprise)
- ✅ Register the ServiceProvider automatically
- ✅ **Register middlewares automatically** in `bootstrap/app.php` (Laravel 11) or via ServiceProvider (Laravel 10)
- ✅ **Configure custom 404 page** - Ask if you want to publish components and views for tenant not found errors

### Manual Installation

[](#manual-installation)

If you prefer manual installation:

```
# Install the package
composer require angelitosystems/filament-tenancy

# Publish the configuration file
php artisan vendor:publish --tag="filament-tenancy-config"

# Publish seeders (now includes central and tenant seeders)
php artisan vendor:publish --tag="filament-tenancy-seeders"
php artisan vendor:publish --tag="filament-tenancy-tenant-seeders"

# Publish custom 404 page components and views (optional)
php artisan vendor:publish --tag="filament-tenancy-views"
php artisan vendor:publish --tag="filament-tenancy-components"

# Run the migrations
php artisan migrate

# Seed default plans (or they will be seeded automatically during installation)
php artisan db:seed --class=Database\Seeders\PlanSeeder

# Setup central database (required for landlord administration)
php artisan filament-tenancy:setup-central --create-admin
```

### Central Database Setup

[](#central-database-setup)

After installation, you need to set up the central database with roles and permissions for the landlord/central administration:

```
# Complete central database setup (recommended)
php artisan filament-tenancy:setup-central --create-admin

# Or step by step:
php artisan migrate --path="packages/filament-tenancy/database/migrations"
php artisan filament-tenancy:seed-central
php artisan filament-tenancy:create-central-admin
```

The central database setup includes:

- 🏛️ **Central Roles &amp; Permissions**: Separate permission system for central administration
- 👑 **Super Admin Role**: Complete access to all central features
- 🛡️ **Landlord Admin Role**: Manage tenants, plans, and subscriptions
- 🎧 **Support Role**: Read-only access for support staff
- 👤 **Central Admin User**: Automatically created with Super Admin role

**Central Permissions Available:**

- `manage tenants` - Create, edit, delete tenants
- `manage plans` - Manage subscription plans
- `manage subscriptions` - Handle tenant subscriptions
- `manage central users` - Manage central admin users
- `manage central roles` - Manage central roles and permissions
- `view central dashboard` - Access central dashboard
- `manage system settings` - Configure system-wide settings
- `access landlord panel` - Access landlord administration panel
- `manage tenant databases` - Manage tenant database operations

### Requirements

[](#requirements)

- **PHP**: 8.1 or higher
- **Laravel**: 10.x or 11.x
- **Filament**: ^4.0
- **Database**: MySQL 5.7+ or PostgreSQL 10+ (SQLite is not supported for multi-database tenancy)

Configuration
-------------

[](#configuration)

The package configuration is located at `config/filament-tenancy.php`. Key configuration options include:

### Tenant Resolution

[](#tenant-resolution)

```
// How tenants are resolved from requests
'resolver' => env('TENANCY_RESOLVER', 'domain'), // 'domain', 'subdomain', 'path'

// Central domains that won't be resolved as tenants
'central_domains' => [
    'app.dental.test',
    'localhost',
    env('APP_DOMAIN', 'localhost'),
],
```

**Note**: The package now supports `APP_DOMAIN` environment variable for subdomain-based tenancy. When creating tenants with subdomains, the package will automatically detect and suggest configuring `APP_DOMAIN` from your `APP_URL` if it's not already set.

### Database Configuration

[](#database-configuration)

```
'database' => [
    'default_connection' => env('DB_CONNECTION', 'mysql'),
    'tenants_connection_template' => [
        'driver' => env('TENANT_DB_DRIVER', 'mysql'),
        'host' => env('TENANT_DB_HOST', '127.0.0.1'),
        'port' => env('TENANT_DB_PORT', '3306'),
        'username' => env('TENANT_DB_USERNAME', 'root'),
        'password' => env('TENANT_DB_PASSWORD', ''),
        // ... other database options
    ],
    'auto_create_tenant_database' => env('TENANCY_AUTO_CREATE_DB', true),
    'auto_delete_tenant_database' => env('TENANCY_AUTO_DELETE_DB', false),
],
```

### Environment Variables

[](#environment-variables)

The package uses the following environment variables:

```
# Base domain for subdomain-based tenancy (auto-detected from APP_URL)
APP_DOMAIN=hola.test

# Tenant resolution strategy
TENANCY_RESOLVER=domain

# Database configuration (optional, uses DB_* by default)
TENANT_DB_DRIVER=mysql
TENANT_DB_HOST=127.0.0.1
TENANT_DB_PORT=3306
TENANT_DB_USERNAME=root
TENANT_DB_PASSWORD=

# Tenancy settings
TENANCY_AUTO_CREATE_DB=true
TENANCY_AUTO_DELETE_DB=false
```

**APP\_DOMAIN**: This variable is automatically detected and configured when creating tenants. If your `APP_URL` contains a valid domain (e.g., `http://hola.test`), the package will ask if you want to use it as `APP_DOMAIN`. This is essential for subdomain-based tenancy.

**Central Domains**: `APP_DOMAIN` is automatically considered a central domain and will not resolve tenants. Additional domains can be configured in `central_domains` config array. Central domains typically host the admin panel for managing tenants. The middleware automatically allows access to these domains without tenant resolution.

**Security**: The middleware automatically:

- Returns 404 for domains/subdomains that don't match any tenant
- Only resolves active tenants (`is_active = true` and not expired)
- Protects central domains from tenant resolution
- Validates tenant status before allowing access

### Filament Integration

[](#filament-integration)

```
'filament' => [
    'auto_register_plugins' => true,
    'landlord_panel_id' => 'admin',
    'tenant_panel_id' => 'tenant',
    'tenant_panel_path' => '/admin',
],
```

Usage
-----

[](#usage)

### Creating Tenants

[](#creating-tenants)

#### Using Artisan Commands (Interactive)

[](#using-artisan-commands-interactive)

The easiest way to create tenants is using the interactive command:

```
# Interactive tenant creation
php artisan tenancy:create
```

The command will guide you through:

- **APP\_DOMAIN Detection**: Automatically detects and configures `APP_DOMAIN` from `APP_URL` if needed
- Tenant name and slug
- Domain or subdomain configuration (subdomains use `APP_DOMAIN` automatically)
- Database name (auto-generated if not provided)
- **Plan selection**: Shows plans from database with prices and billing cycles (Basic, Premium, Enterprise)
- Active status and expiration date
- **Automatic subscription creation**: Creates an active subscription when a plan is selected

**APP\_DOMAIN Auto-Configuration**:

- **Valid Domain Detection**: If `APP_URL` contains a valid domain (e.g., `http://hola.test`), the command will detect it and ask if you want to use it as `APP_DOMAIN`
- **Localhost/Port Detection**: If `APP_URL` is localhost or has a port (e.g., `http://localhost:8000`), you'll be prompted to configure `APP_DOMAIN` manually
- **Automatic .env Updates**: The `APP_DOMAIN` variable is automatically added or updated in your `.env` file
- **Subdomain Support**: When using subdomains, the full domain is automatically constructed using `APP_DOMAIN` (e.g., `tenant.APP_DOMAIN`)

#### Creating Tenant Users

[](#creating-tenant-users)

Create users for specific tenants with roles and permissions:

```
# Interactive mode
php artisan tenant:user-create

# Non-interactive mode
php artisan tenant:user-create \
    --tenant="my-tenant" \
    --name="John Doe" \
    --email="john@example.com" \
    --role="admin" \
    --permissions="manage users,view dashboard"

# List available options
php artisan tenant:user-create --list-tenants
php artisan tenant:user-create --tenant="my-tenant" --list-roles
php artisan tenant:user-create --tenant="my-tenant" --list-permissions
```

**Features:**

- Interactive tenant selection with numbered options
- Automatic password generation
- Role and permission assignment
- Email validation
- Comprehensive user information display

#### Using Artisan Commands (Non-Interactive)

[](#using-artisan-commands-non-interactive)

```
# Create a new tenant with all options (plan slug must exist in database)
php artisan tenancy:create "Acme Corp" \
    --subdomain="acme" \
    --database="acme_db" \
    --plan="premium" \
    --active \
    --expires="2025-12-31"

# Create with domain
php artisan tenancy:create "Acme Corp" --domain="acme.com"

# Create with subdomain
php artisan tenancy:create "Acme Corp" --subdomain="acme"
```

**Note**: When using `--plan`, the plan slug must exist in the `tenancy_plans` table. If a plan is provided, a subscription will be automatically created for the tenant.

#### Programmatically

[](#programmatically)

```
use AngelitoSystems\FilamentTenancy\Facades\Tenancy;

// Create a new tenant
$tenant = Tenancy::createTenant([
    'name' => 'Acme Corporation',
    'slug' => 'acme-corp',
    'domain' => 'acme.com',
    'is_active' => true,
]);

// Switch to tenant context
Tenancy::switchToTenant($tenant);

// Run code in tenant context
Tenancy::runForTenant($tenant, function () {
    // This code runs in the tenant's database context
    User::create(['name' => 'John Doe', 'email' => 'john@acme.com']);
});

// Switch back to central context
Tenancy::switchToCentral();
```

### Working with Models

[](#working-with-models)

#### User Model with Roles &amp; Permissions

[](#user-model-with-roles--permissions)

Add the `HasRoles` trait to your User model to enable role-based access control:

```
