Tenancy for Laravel

repository·master·Indexed 26 days ago

https://github.com/archtechx/tenancy

A Laravel package providing automatic multi-tenancy. It features automatic database connection switching, hostname-based tenant identification, and support for Row Level Security (RLS) in PostgreSQL. The package includes a suite of Artisan commands for managing tenant migrations (tenants:migrate, tenants:rollback), handling symbolic links (tenants:link), and managing tenant lifecycles via pending tenant creation and cleanup.

Tokens
6.4K
Snippets
1
Records
57
Agent score
88%

What's inside archtechx-tenancy

  1. Overview of Tenancy for Laravel

    master

    Tenancy for Laravel provides automatic multi-tenancy for Laravel applications. It is designed to work without requiring significant changes to your existing application code.

    Key features include:

    • Automatic database connection switching without needing to add model traits.
    • No need to replace core Laravel classes (such as Cache or Storage) with tenancy-aware versions.
    • Built-in tenant identification based on the hostname, supporting second-level domains.
  2. Install Tenancy for Laravel

    master

    Run the tenancy:install command to perform the initial setup of the package. This command automates the following tasks:

    • Publishing configuration: Creates config/tenancy.php.
    • Publishing routes: Creates routes/tenant.php.
    • Publishing service provider: Creates app/Providers/TenancyServiceProvider.php.
    • Publishing migrations: Creates the core tenant and domain tables via database/migrations/2019_09_15_000010_create_tenants_table.php and database/migrations/2019_09_15_000020_create_domains_table.php.
    • Creating migration directory: Creates the database/migrations/tenant folder for tenant-specific migrations.

    Note: If files already exist, the command will issue a warning and skip those specific steps to prevent overwriting your existing configuration.

  3. Configure the test environment via Docker Compose

    master

    The docker-compose.yml file defines a comprehensive testing environment for the tenancy package, including multiple database engines and caching layers. You can customize the build and runtime behavior using several environment variables.

    Build Arguments

    • PHP_VERSION: Sets the PHP version for the test container (defaults to 8.4).
    • XDEBUG_ENABLED: Enables or disables Xdebug (defaults to false).

    Environment Variables

    • PROJECT_PATH: Sets the working directory and volume mount path (defaults to $PWD).
    • DB_PASSWORD, DB_USERNAME, DB_DATABASE: Configures the primary database connection for the test container.

    Database Connection Hosts

    The test container uses the following environment variables to locate the various service dependencies:

    • TENANCY_TEST_REDIS_HOST: Host for Redis.
    • TENANCY_TEST_MYSQL_HOST: Host for MySQL.
    • TENANCY_TEST_PGSQL_HOST: Host for PostgreSQL.
    • TENANCY_TEST_SQLSRV_HOST: Host for MSSQL.
    • TENANCY_TEST_SQLSRV_USERNAME: Username for MSSQL.
    • TENANCY_TEST_SQLSRV_PASSWORD: Password for MSSQL (must match SA_PASSWORD in the mssql service).
  4. Configure PathTenantResolver via configuration

    master

    The PathTenantResolver identifies tenants using URL path parameters. You can customize its behavior by adding configuration keys under tenancy.identification.resolvers.Stancl\Tenancy\Resolvers\PathTenantResolver in your Laravel configuration files.

    Available configuration keys:

    • tenant_parameter_name: The name of the route parameter used to identify the tenant (defaults to 'tenant').
    • tenant_route_name_prefix: The prefix used for tenant-specific route names (defaults to 'tenant.').
    • tenant_model_column: The database column on the tenant model used for identification (defaults to the tenant model's primary key).
    • allowed_extra_model_columns: An array of additional model columns that are permitted to be used for tenant identification. If a route uses a binding field not in this list or the default column, a TenantColumnNotWhitelistedException will be thrown.
  5. Configure data deletion during migrate:fresh

    master

    You can control whether the tenant model's data is deleted before running a fresh migration by setting the drop_tenant_databases_on_migrate_fresh key in your tenancy configuration file.

    Set this to true to trigger the deletion of all records in the tenant model's table before the fresh migration process begins.

  6. Configure TraitRLSManager settings

    master

    The TraitRLSManager class provides several static properties to control how Row Level Security (RLS) policies are discovered and applied to your Eloquent models. You can configure these properties to customize model discovery, RLS scoping behavior, and exclusions.

    • $modelDirectories: An array of directories to scan for models. Subdirectories are included. Use 'app/Models/*' to scan subdirectories but exclude models directly in app/Models.
    • $implicitRLS: If set to true, all discovered models will be scoped using RLS by default. If false, you must implement the RLSModel interface on specific models to enable RLS.
    • $excludedModels: An array of class names to skip during the discovery process.
    • $modelDiscoveryOverride: A closure that allows you to manually return an array of Model instances, bypassing the directory scanning logic.
  7. Configure TenancyUrlGenerator behavior

    master

    The TenancyUrlGenerator class (used when UrlGeneratorBootstrapper is enabled) provides several static properties to control how tenant-aware URLs are generated. These properties allow you to automate tenant parameter injection and route name prefixing.

    Available Configuration Properties

    PropertyTypeDescription
    static::$bypassParameterstringThe key used in the parameters array to bypass tenancy modifications. Defaults to 'central'.
    static::$prefixRouteNamesboolIf true, prepends the tenant route name prefix (e.g., tenant.) to route names. Useful for route cloning.
    static::$passTenantParameterToRoutesboolIf true, automatically passes the tenant parameter to route() calls. Useful for query parameter identification.
    static::$overridesarrayA mapping of original route names to tenant-specific route names (e.g., ['profile.show' => 'tenant.profile.show']).
    static::$passQueryParameterboolIf true and $passTenantParameterToRoutes is enabled, uses the query_parameter config instead of the path parameter name. Defaults to true.
  8. Manage tenant database connections with DatabaseManager

    master

    The Stancl\Tenancy\Database\DatabaseManager class provides methods to switch between central and tenant database connections.

    • Use connectToTenant(TenantWithDatabase $tenant) to switch the application's default connection to the tenant's database.
    • Use reconnectToCentral() to purge the tenant connection and revert to the central connection defined in tenancy.database.central_connection.
    • Use purgeTenantConnection() to remove the tenant connection from the database manager and the configuration.