toporia/tenancy

Multi-tenancy support for Toporia Framework

Installs: 0

Dependents: 0

Suggesters: 1

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/toporia/tenancy

dev-main 2025-12-16 04:00 UTC

This package is auto-updated.

Last update: 2025-12-16 04:01:00 UTC


README

Multi-tenancy support for Toporia Framework.

Installation

composer require toporia/tenancy

Auto-Discovery

This package uses Toporia's Package Auto-Discovery system. After installation:

  • Service Provider is automatically registered - no manual registration required
  • Configuration is automatically discovered from extra.toporia.config in composer.json
  • Migrations are automatically included when running php console migrate

To rebuild the package manifest manually:

php console package:discover

Setup

Publish Config (optional)

php console vendor:publish --provider="Toporia\Tenancy\TenancyServiceProvider"
# Or with tag
php console vendor:publish --tag=tenancy-config

Or manually copy packages/tenancy/config/tenancy.php to config/tenancy.php.

Usage

1. Create Tenant Model

use Toporia\Tenancy\Contracts\TenantInterface;

class Tenant extends Model implements TenantInterface
{
    public function getTenantKey(): int|string
    {
        return $this->id;
    }

    public function getTenantIdentifier(): string
    {
        return $this->slug;
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }
}

2. Add BelongsToTenant to Models

use Toporia\Tenancy\Concerns\BelongsToTenant;

class Product extends Model
{
    use BelongsToTenant;
}

// Queries automatically filtered by tenant_id
$products = Product::all(); // WHERE tenant_id = current_tenant_id

// Bypass tenant scope (admin operations)
$allProducts = Product::withoutTenantScope()->get();

3. Use Middleware

// routes/api.php
$router->group(['middleware' => ['tenant']], function ($router) {
    $router->get('/products', [ProductController::class, 'index']);
});

4. Helper Functions

tenant();           // Get current tenant
tenant_id();        // Get current tenant ID
has_tenant();       // Check if tenant context exists
run_as_tenant($tenant, fn() => ...);    // Run in tenant context
run_without_tenant(fn() => ...);        // Run without tenant scope

Configuration

// config/tenancy.php
return [
    'enabled' => true,
    'model' => App\Domain\Entities\Tenant::class,
    'column' => 'tenant_id',

    'resolvers' => [
        'subdomain' => ['enabled' => false, 'base_domain' => 'example.com'],
        'header' => ['enabled' => true, 'name' => 'X-Tenant-ID'],
        'path' => ['enabled' => false],
    ],
];

License

MIT