PHP code example of angelitosystems / filament-tenancy

1. Go to this page and download the library: Download angelitosystems/filament-tenancy library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

angelitosystems / filament-tenancy example snippets


// 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'),
],

'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),
],

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

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' => '[email protected]']);
});

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



namespace App\Models;

use AngelitoSystems\FilamentTenancy\Concerns\HasRoles;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasRoles;
    
    // Your model code...
}

// Assign roles
$user->assignRole('admin');
$user->syncRoles(['admin', 'editor']);

// Check roles
$user->hasRole('admin');
$user->hasAnyRole(['admin', 'editor']);

// Assign permissions
$user->givePermissionTo('manage users');
$user->syncPermissions(['manage users', 'view dashboard']);

// Check permissions
$user->hasPermissionTo('manage users');
$user->hasAnyPermission(['manage users', 'edit posts']);

use AngelitoSystems\FilamentTenancy\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use BelongsToTenant;
    
    // Your model code...
}

use AngelitoSystems\FilamentTenancy\Concerns\UsesLandlordConnection;
use Illuminate\Database\Eloquent\Model;

class Plan extends Model
{
    use UsesLandlordConnection;
    
    // Your model code...
}

// app/Providers/Filament/AdminPanelProvider.php
use AngelitoSystems\FilamentTenancy\FilamentPlugins\TenancyLandlordPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        ->id('admin')
        ->path('/admin')
        ->plugin(TenancyLandlordPlugin::make())
        // ... other panel configuration
}

// app/Providers/Filament/TenantPanelProvider.php
use AngelitoSystems\FilamentTenancy\FilamentPlugins\TenancyTenantPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        ->id('tenant')
        ->path('/admin')
        ->plugin(TenancyTenantPlugin::make())
        // ... other panel configuration
}

use AngelitoSystems\FilamentTenancy\Events\TenantCreated;

Event::listen(TenantCreated::class, function (TenantCreated $event) {
    // Handle tenant creation
    $tenant = $event->tenant;
});

use AngelitoSystems\FilamentTenancy\Support\TenantResolver;

class CustomTenantResolver extends TenantResolver
{
    public function resolve(Request $request): ?Tenant
    {
        // Your custom resolution logic
        return parent::resolve($request);
    }
}

// Register in a service provider
$this->app->bind(TenantResolver::class, CustomTenantResolver::class);

$tenant = Tenant::find(1);
$tenant->update([
    'database_host' => 'custom-host.com',
    'database_name' => 'custom_database',
    'database_username' => 'custom_user',
    'database_password' => 'custom_password',
]);

$tenant->data = [
    'settings' => [
        'theme' => 'dark',
        'timezone' => 'UTC',
    ],
    'features' => ['feature1', 'feature2'],
];
$tenant->save();

// Access data
$theme = $tenant->data['settings']['theme'] ?? 'light';

// With APP_DOMAIN=hola.test configured
$tenant = Tenant::create([
    'name' => 'Acme Corp',
    'subdomain' => 'acme',
]);

echo $tenant->getFullDomain(); // Output: acme.hola.test
echo $tenant->getUrl(); // Output: http://acme.hola.test

use AngelitoSystems\FilamentTenancy\Support\DebugHelper;

// Only logs when APP_ENV=local AND APP_DEBUG=true
DebugHelper::info('Tenant created', ['tenant_id' => $tenant->id]);
DebugHelper::debug('Connection details', $connectionData);
DebugHelper::warning('Potential issue detected', $context);

// Always logs regardless of environment
DebugHelper::error('Critical error occurred', $errorData);
DebugHelper::critical('System failure', $criticalData);
bash
# 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
bash
# Interactive tenant creation
php artisan tenancy:create
bash
# Interactive mode
php artisan tenant:user-create

# Non-interactive mode
php artisan tenant:user-create \
    --tenant="my-tenant" \
    --name="John Doe" \
    --email="[email protected]" \
    --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
bash
# Publish views (Blade templates)
php artisan vendor:publish --tag="filament-tenancy-views"

# Publish Livewire component (optional, 
bash
php artisan make:migration create_tenant_users_table --path=database/migrations/tenant
bash
# Run migrations for specific tenant
php artisan tenant:migrate

# Rollback tenant migrations
php artisan tenant:rollback

# Fresh tenant database
php artisan tenant:fresh
bash
# Monitor tenant connections
php artisan filament-tenancy:monitor-connections