smorken/tenancy

Opinionated stancl tenancy helper

dev-main / 10.x-dev 2023-06-13 19:31 UTC

This package is auto-updated.

Last update: 2024-12-13 22:36:22 UTC


README

Uses stancl/tenancy

Install tenancy config and tenant migrations directory

$ php artisan tenancy:installer

Migrating/seeding

Central/Landlord

$ php artisan migrate [--seed]

Tenants

stancl/tenancy console commands

Edit config/tenancy.php migration_parameters and seeder_parameters

$ php artisan tenants:migrate [--tenants=TENANT_ID]
$ php artisan tenants:seed [--tenants=TENANT_ID] 
$ php artisan tenants:run role:set --argument="user_id=12345"

Splitting routes/verifying a tenant early

You can use a Preloader to bring back the tenant without initializing tenancy.

In the example below, the DomainPreloader is used in conjunction with the InitializeTenancyByDomain middleware (to actually initialize tenancy).

app/Providers/RouteServiceProvider.php

public function boot(): void
{
    $this->configureRateLimiting();

    $this->routes(function () {
        $tenant = $this->preloadTenant();
        if (!$tenant) {
            Route::prefix('api')
                 ->middleware('api')
                 ->namespace($this->namespace)
                 ->group(base_path('routes/api.php'));
            Route::middleware('web')
                 ->namespace($this->namespace)
                 ->group(base_path('routes/web.php'));
        } else {
            Route::namespace($this->namespace)
                 ->middleware([
                     'web',
                     InitializeTenancyByDomain::class,
                     PreventAccessFromCentralDomains::class,
                 ])
                 ->group(base_path('routes/tenant.php'));
        }
    });
}

protected function preloadTenant(): ?Tenant
    {
        if ($this->app->runningInConsole()) {
            return null;
        }
        /** @var \Smorken\Tenancy\Contracts\Preloaders\Preloader $loader */
        $loader = $this->app->make(DomainPreloader::class);
        return $loader->load($this->app['request']);
    }