Search by

kaushalbro / quick-laravel-saas

kaushal ghimire

All-in-one modular Laravel 5.5-16+ multi-tenant SaaS engine, billing, subscriptions, org/branch RBAC, and self-contained Developer Center.

Package info

github.com/kaushalbro/quick-laravel-saas

pkg:composer/kaushalbro/quick-laravel-saas

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.0 2026-11-30 19:24 UTC

This package is not auto-updated.

Last update: 2026-11-30 23:46:56 UTC


README

All-in-one modular Laravel 5.5–13+ multi-tenant SaaS engine (PHP 7.0–8.4+), including isolated tenant/branch/client databases, hierarchical central organizations (parent_organization_id) & branches, inter-database querying & syncing (TenantDB), domain routing, subscriptions, coupons, billing & invoicing, entitlements, usage quotas, audit logging, encrypted backups, Saas + companion facades, Artisan CLI, and a self-contained Developer Center (/ghimire-saas/*).

Works with any Laravel client stack — Blade, Livewire, Inertia (React/Vue), or API-only — with zero Node/npm build required in your client application.

Requirements

  • PHP: >=7.0 (7.0–8.4+)
  • Laravel: >=5.5 (5.5–13+)
  • Database: MySQL / MariaDB (recommended), PostgreSQL, or SQLite

1. Installation

Step 1: Install via Composer

composer require ghimire/laravel-saas

Step 2: Configure .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_central_db
DB_USERNAME=root
DB_PASSWORD=secret

GHIMIRE_TENANT_DB_PREFIX=myapp_tenant_

SESSION_DRIVER=database
SESSION_DOMAIN=null
QUEUE_CONNECTION=database
CACHE_STORE=database

# Optional: Multi-level Organization Landlord DBs (org_landlord_1, org_landlord_2, ...) & Portal
SAAS_HIERARCHICAL_DB_ENABLED=true
SAAS_ORGANIZATION_DB_ENABLED=true
SAAS_BRANCH_CLIENT_ENABLED=true
SAAS_ORG_SCHEMA=new_erp_landlord
SAAS_ORG_INCLUDE_TENANT_MIGRATIONS=false
SAAS_DB_ORG_PATTERN="org_landlord_{organization_id}"

# Optional: Main App domain + nested subdomain base hosts (e.g. saas.vritico.com + *.vritico.com)
GHIMIRE_DEVELOPER_CENTER_DOMAIN=saas.vritico.com
GHIMIRE_SUBDOMAIN_BASE_HOSTS=saas.vritico.com,vritico.com

# Optional: Seeded Organization Super Admin credentials inside each org_landlord_{id}
GHIMIRE_ORG_ADMIN_NAME="Organization Super Admin"
GHIMIRE_ORG_ADMIN_EMAIL=superadmin@organization.local
GHIMIRE_ORG_ADMIN_PASSWORD=StrongPassword@123

Setting SESSION_DOMAIN=null keeps cookies host-only so logging into store1.local or org1 never affects store2.local or org2.

Step 3: Register Tenant & Organization Identification Middleware (Web & API)

Prepend ResolveTenantByDomainOrSubdomainMiddleware (or ResolveTenantByDomainMiddleware for exact custom domains only) so tenant, organization (org_landlord_{id}), branch, and client database resolution runs before StartSession across all web and api routes:

Laravel 11, 12 & 13 (bootstrap/app.php):

use Illuminate\Foundation\Configuration\Middleware;

->withMiddleware(function (Middleware $middleware): void {
    $middleware->prepend(\Ghimire\SaaS\Http\Middleware\Domain\ResolveTenantByDomainOrSubdomainMiddleware::class);
})

Laravel 8, 9 & 10 (app/Http/Kernel.php):

protected $middleware = [
    \Ghimire\SaaS\Http\Middleware\Domain\ResolveTenantByDomainOrSubdomainMiddleware::class,
    // ...existing global middleware
];

Step 4: Publish Config (Optional)

php artisan vendor:publish --tag=ghimire-saas-config

Step 5: Run Central Migrations & Seed Super Admin

Your existing database/migrations/ folder stays untouched for tenant databases. Any central-only app migrations go in database/migrations/central/.

php artisan migrate
php artisan db:seed --class="Ghimire\\SaaS\\Database\\Seeders\\SaasUserSeeder"

Step 6: Open Developer Center

Visit /ghimire-saas/login in your browser:

  • Email: superadmin@ghimire.local
  • Password: password

(For headless/API-only apps that don't want the admin UI routes, set GHIMIRE_DEVELOPER_CENTER_ENABLED=false in .env.)

2. How Multi-Tenancy & Hierarchy Work

  • Central Database: Stores saas_tenants, saas_domains, saas_organizations (with optional parent_organization_id parent→child hierarchy plus slug, email, contact_number), saas_branches (with parent_branch_id), saas_clients, saas_managed_databases, saas_database_servers, saas_user_memberships, billing/subscriptions, settings, audits, backups, saas_users, and framework sessions/cache/jobs.
  • Database Ownership: Organizations, Branches, Branch Clients, and Tenants can each own isolated/managed databases (when organization_database_enabled is false, Organizations act as database-less grouping entities).
  • Tenant / Branch / Client Databases: Contain only your client app's own tables (users, products, orders, etc.) — zero extra tenancy control-plane tables polluting your workspace schemas.
  • Auto-Migrate & Auto-Seed: Creating a tenant automatically creates its isolated database, runs all migrations in database/migrations/ (plus module tenant migrations), and runs TenantDatabaseSeeder + your app's Database\Seeders\DatabaseSeeder.

2a. Organization Landlord Database (org_landlord_{organization_id}) & Dual Organization Portal

When SAAS_HIERARCHICAL_DB_ENABLED=true and SAAS_ORGANIZATION_DB_ENABLED=true, each Organization receives an isolated database named org_landlord_{organization_id} (org_landlord_1, org_landlord_2, org_landlord_3, ...):

  • Strict new_erp_landlord Schema (database/migrations/organization/): Contains organizations, tenants, users (tenant_id, primary_tenant_id, boolean status, blocked, is_super), user_accessible_tenants (unique(user_id, tenant_id)), global_email_configurations, global_organizations, global_s3_configurations, password_reset_tokens, sessions, jobs, job_batches, and failed_jobs (SAAS_ORG_INCLUDE_TENANT_MIGRATIONS=false keeps tenant app migrations out of org landlord DBs).
  • Idempotent Single Super Admin (OrganizationDatabaseSeeder): Provisions the owning organizations row, baseline global_organizations defaults, and one Super Admin user (is_super = true, status = true, blocked = false) without creating duplicates on repeated migrate/seed/sync runs.
  • Duplicate-Free Sync (ParentHierarchySyncService / php artisan saas:sync-hierarchy): Syncs Organizations, Tenants (db_password encrypted via Crypt when SAAS_ORG_ENCRYPT_TENANT_DB_PASSWORD=true), Users, and user_accessible_tenants pivots cleanly into parent org_landlord_{id} DBs without duplicating rows.

Accessing the Organization Portal (Path Mode & Domain/Subdomain Mode)

Both URL structures point to the exact same OrganizationPortalController + Inertia UI and are isolated per Organization session (_ghimire_org_portal_org_id + _ghimire_org_portal_user_id):

Portal Page Central App Path (ghimire.org.*) Organization Domain / Subdomain (ghimire.org_domain.*)
Login /organizations/{org}/login https://{org-domain}/login
Dashboard /organizations/{org}/dashboard https://{org-domain}/dashboard
Tenants /organizations/{org}/tenants https://{org-domain}/tenants
Branches /organizations/{org}/branches https://{org-domain}/branches
Clients /organizations/{org}/clients https://{org-domain}/clients
Users & Access /organizations/{org}/users https://{org-domain}/users
Global Settings /organizations/{org}/settings https://{org-domain}/settings

OrganizationDomainValidator ensures {org-domain}/... routes match only verified Organization portal hosts (domain_type === 'organization'), so central routes (/login, /dashboard) and tenant/branch/client ERP domains are never shadowed. Assets are served same-origin via PackageAssetController even when GHIMIRE_DEVELOPER_CENTER_DOMAIN pins Developer Center to a separate central host.

2b. Multi-Level Domains & Nested Subdomains (saas.vritico.com + abc.bcd.cde.vritico.com)

The package supports hosting the Main App / Developer Center on a subdomain (e.g. saas.vritico.com) alongside multi-label domains and nested hierarchical subdomains (abc.bcd.cde.vritico.com):

APP_URL=https://saas.vritico.com
GHIMIRE_DEVELOPER_CENTER_DOMAIN=saas.vritico.com
GHIMIRE_SUBDOMAIN_BASE_HOSTS=saas.vritico.com,vritico.com
  • Central Host Safety: saas.vritico.com (APP_URL, developer_center.domain, subdomain_base_hosts) is excluded by TenantIdentificationPipeline::isCentralHost(), so visiting https://saas.vritico.com/ghimire-saas or https://saas.vritico.com/organizations/{org}/dashboard never resolves as a subdomain tenant saas.
  • Explicit Multi-Label Domains & Subdomains: Both custom domains (DomainService::assertValidHostname) and subdomain inputs (DomainService::sanitizeSubdomainLabel / frontend normalizeSubdomainInput) accept dotted multi-label hostnames like abc.bcd.cde.vritico.com (typing abc.bcd.cde with base vritico.com, or pasting the full host, preserves dots cleanly in Developer Center across Tenants, Organizations, Branches, Branch Clients, and Domains).
  • Dynamic Right-to-Left Hierarchical Lookup: If no explicit saas_domains record matches abc.bcd.cde.vritico.com, TenantIdentificationPipeline::resolveBySubdomain() resolves right-to-left (cde = Organization or Tenant -> bcd = Branch -> abc = Client or sub-branch), populates TenantContext (organization(), branch(), client()), and switches into the deepest target database automatically.

3. One-Call Fluent Provisioning (Saas::provision & Saas::forTenant)

Facade: Ghimire\SaaS\Facades\Saas

Create a Tenant (One Call)

use Ghimire\SaaS\Facades\Saas;

$result = Saas::provision('Acme Store')
    ->type('organization') // 'main' | 'organization' | 'branch'
    ->organization('Acme Holdings', currency: 'NPR', timezone: 'Asia/Kathmandu')
    ->branches([
        ['name' => 'HQ Branch', 'city' => 'Kathmandu'],
        'Pokhara Branch:Pokhara',
    ])
    ->domains(['acme.local', 'shop.acme.local']) // or 'acme.local, shop.acme.local'
    ->plan('PRO_PLAN', billingPeriod: 'monthly') // or ->planId($planId, $priceId)
    ->coupon('WELCOME20')                        // or ->couponId($couponId)
    ->trialDays(14)
    ->run();

$tenant = $result['tenant'];

Update / Manage an Existing Tenant

// Update name, add domains, change plan, re-run migrations/seeders
Saas::forTenant('TENANT-000001') // accepts Tenant model, code, or ID
    ->name('Acme Store V2')
    ->domains('vip.acme.local')
    ->plan('ENTERPRISE', 'yearly')
    ->coupon('VIP50')
    ->migrate()
    ->seed()
    ->update(); // or ->run()

// Lifecycle actions
Saas::forTenant('TENANT-000001')->suspend();
Saas::forTenant('TENANT-000001')->activate();
Saas::forTenant('TENANT-000001')->delete(dropDatabase: true);

4. Complete Facades, Accessors & Response Payloads Reference

A. Registered Facades (Auto-Discovered)

Facade Alias Underlying Service Description Usage Example
Ghimire\SaaS\Facades\Saas Saas Ghimire\SaaS\SaasManager Unified entry point for all SaaS services, resources & provisioning Saas::tenants()->findByCode('TENANT-000001')
Ghimire\SaaS\Facades\TenantDB TenantDB Ghimire\SaaS\Services\Database\InterDatabaseManager Cross-DB queries, batched hydration, fan-out aggregation, transfers & multi-DB transactions TenantDB::branch('BRN-000001')->table('orders')->get()
Ghimire\SaaS\Facades\SaasContext SaasContext Ghimire\SaaS\Contracts\TenantContextContract Active tenant, organization, branch, client & resolved DB context SaasContext::branchCode()
Ghimire\SaaS\Facades\SaasSettings SaasSettings Ghimire\SaaS\Services\Settings\SettingsManager Cascading package settings across tenant, org, branch & user scopes SaasSettings::package('pos')->forBranch('BRN-000001')->get('tax_rate')
Ghimire\SaaS\Facades\SaasBilling SaasBilling Ghimire\SaaS\Services\Billing\BillingService Invoices, VAT calculation, payments & credit notes SaasBilling::issue($invoice)

B. All Saas Facade Accessors & Methods (SaasManager)

1. Tenancy, Provisioning & Context

Accessor / Method Returns Description Example Call & Sample Output
Saas::tenants() / Saas::tenancy() TenantManager Create, migrate, seed, suspend, activate, delete & iterate active tenants Saas::tenants()->migrate($tenant) → ['tenant_id' => 1, 'ran' => true]
Saas::provision($name = null) TenantProvisioner Fluent one-call tenant creation with org, branches, domains, plan & coupon Saas::provision('Acme')->organization('Acme HQ')->run() → ['tenant' => Tenant, 'organization_code' => 'ORG-000001', ...]
Saas::forTenant($tenant) TenantProvisioner Fluent management/updates for an existing tenant (model, ID, or TENANT-* code) Saas::forTenant('TENANT-000001')->migrate()->update()
Saas::context() TenantContextContract Active tenancy/hierarchy state container (tenant(), organization(), branch(), client()) Saas::context()->isInitialized() → true
Saas::currentTenant() TenantContract|null Returns the currently initialized active tenant or null Saas::currentTenant()->code() → 'TENANT-000001'
Saas::central(Closure $fn) mixed Safely runs $fn in central DB context and restores previous tenant context in finally Saas::central(fn () => Plan::count()) → 3
Saas::tenantBatch($jobs, $tenant = null) PendingBatch Dispatches a tenant-scoped Laravel Bus batch inheriting active/target tenant Saas::tenantBatch([new SyncJob()])->dispatch()
Saas::conversion() ConversionEngine Inspects & adopts single-tenant Laravel apps into multi-tenant SaaS Saas::conversion()->inspect()

2. Hierarchical Databases & Inter-Database Access

Accessor / Method Returns Description Example Call & Sample Output
Saas::db() InterDatabaseManager Inter-DB queries (central(), tenant(), branch(), client()), hydrate(), transfer(), transaction(), compareSchema() Saas::db()->sumAcross('branch', $org, 'orders', 'total') → 1600.0
Saas::database() HierarchicalDatabaseManager Provision, migrate, seed, rollback, backup, restore, health-check, inspect & move branch/client/tenant DBs Saas::database()->forBranch($b)->healthCheck() → ['healthy' => true, 'latency_ms' => 3, ...]
Saas::databaseServers() DatabaseServerRegistry Register, update, test health, set default & manage multi-server DB pool Saas::databaseServers()->all() → Collection<DatabaseServer>

3. Domains, Organizations, Branches & User Access Context

Accessor / Method Returns Description Example Call & Sample Output
Saas::domains() DomainService Register custom domains/subdomains, verify DNS, set primary & invalidate cache Saas::domains()->register($tenant, 'app.acme.test', 'tenant')
Saas::organizations() OrganizationService Create/update/delete grouping orgs with parent_organization_id nesting & cycle guard + assignMembership() Saas::organizations()->create('Sub Org', ['parent_organization_id' => 1])
Saas::branches() BranchService Create/update/delete branches with parent_branch_id, setMain(), assignMembership() Saas::branches()->create($org, 'KTM Branch', ['city' => 'Kathmandu'])
Saas::user() UserAccessHelper Host-user branch access checks (inMainBranch(), assignedBranches(), switchBranch()) Saas::user()->hasBranchAccess('BRN-000002') → true
Saas::userContext() UserContextService Fluent all-in-one host user context resolver & payload filter Saas::userContext()->resolve(['user', 'hierarchy'])
Saas::me($sections = null, $opts = []) array Shortcut returning all-in-one SaaS context (meta, user, tenant, hierarchy, subscription, entitlements, ...) Saas::me('minimal') → ['meta' => ..., 'user' => ..., 'tenant' => ..., 'hierarchy' => ...]
Saas::switchBranch($code, $sec = null, $opts = []) array Switches active session/header branch and returns refreshed me() payload Saas::switchBranch('BRN-000002') → ['hierarchy' => ['active_branch' => ...], ...]
Saas::users() SaasResourceBuilder Query/mutation builder scoped to Developer Center saas_users Saas::users()->where('status', 'active')->get()

4. Commercial, Billing, Quotas, Settings & Platform Ops

Accessor / Method Returns Description Example Call & Sample Output
Saas::plans() / Saas::coupons() PlanService / CouponService Create/update plans, multi-currency prices, features & percentage/fixed coupons Saas::plans()->allActive()
Saas::subscriptions() SubscriptionService Subscribe, switch plans with decimal-safe proration, cancel, renew & extend trial Saas::subscriptions()->subscribe($tenant, $plan, $price, 14)
Saas::billing() / Saas::payments() BillingService / PaymentGatewayManager Draft/issue VAT invoices, credit notes, record payments & dispatch/replay gateways Saas::billing()->createDraftInvoice($tenant, $sub, $items)
Saas::entitlements() / Saas::usage() EntitlementService / UsageService Feature checks & atomic quota consumption/rollbacks Saas::entitlements()->hasFeature($tenant, 'api_access') → true
Saas::settings() / Saas::centralSettings() SettingsManager / CentralSettingsService Cascading tenant→org→branch→user package settings & central system config Saas::settings()->package('pos')->forBranch('BRN-000001')->get('currency') → 'NPR'
Saas::files() FileManager Tenant/org/branch-isolated local or S3 storage (put, url, tenantAsset) Saas::files()->forTenant($tenant)->url('logos/store.png')
Saas::audit() / Saas::backups() AuditLogger / BackupManager Immutable audit trail & SHA-256 verified encrypted backups/restore/dry-run Saas::backups()->backupTenant($tenant, null, true)
Saas::health() HealthCheckManager PHP version, DB connection & cache diagnostics Saas::health()->runAll() → ['ok' => true, 'checks' => [...]]
Saas::packages() / Saas::modules() PackageRegistryContract / ModuleRegistryContract Discover & inspect registered add-on packages & tenant modules Saas::modules()->all()

5. Unified Resource Gateway (ResourceRegistry via Saas::*By)

Method Purpose Example Call
Saas::resources() Returns ResourceRegistry (keys() lists all registered resource names & aliases) Saas::resources()->keys()
Saas::resource($name) Returns fluent SaasResourceBuilder (forTenant(), where(), with(), paginate(), get(), post()) Saas::resource('branches')->where('status', 'active')->paginate(15)
Saas::getBy($resource, $params = [], $opts = []) Allowlisted filter, sort, search & relation eager-load query Saas::getBy('plans', ['is_active' => true, 'currency' => 'NPR'], ['with' => ['prices']])
Saas::findBy($resource, $criteriaOrId, $opts = []) Single record lookup by ID, code, slug, domain, or criteria array Saas::findBy('tenants', 'TENANT-000001', ['with' => ['database', 'domains'], 'or_fail' => true])
Saas::existsBy($resource, $criteria, $opts = []) Boolean existence check Saas::existsBy('domains', ['domain' => 'acme.local']) → true
Saas::countBy($resource, $criteria = [], $opts = []) Integer count of matching records Saas::countBy('branches', ['status' => 'active'], ['tenant' => $tenant]) → 3
Saas::postBy($resource, $payload, $match = [], $opts = []) Validated create or idempotent upsert when $match matches Saas::postBy('plans', ['name' => 'Growth', 'monthly_price' => '2500.00'], ['code' => 'GROWTH'])
Saas::updateBy($resource, $target, $payload, $opts = []) Validated single or opt-in bulk update (['allow_bulk' => true]) Saas::updateBy('branches', 'BRN-000002', ['city' => 'Pokhara'])
Saas::deleteBy($resource, $target, $opts = []) Guarded deletion preserving business invariants Saas::deleteBy('coupons', 'OLD20') → true
Saas::action($resource, $action, $target, $payload, $opts) Named workflow action dispatcher (e.g. issue, verify, suspend, set_main) Saas::action('invoices', 'issue', $invoiceId)

Supported Resource Keys: tenants, domains, organizations, branches, memberships, plans, plan_prices, plan_features, coupons, subscriptions, invoices, credit_notes, payments, payment_webhooks, entitlements, usage, settings, central_settings, audit_logs, backups, saas_users.

C. Sample Response Payloads

1. Saas::provision(...)->run()

[
    'tenant' => Tenant, // App/package Tenant model with loaded `database` relation
    'organization_code' => 'ORG-000001',
    'branch_codes' => ['BRN-000001', 'BRN-000002'],
    'domains' => [Domain, Domain],
    'subscription' => Subscription, // or null if no plan given
]

2. Saas::me() / Saas::switchBranch('BRN-000001')

{
    "meta": {
        "resolved_at": "2026-11-28T22:00:00+05:45",
        "guard": "web",
        "authenticated": true,
        "has_tenant_context": true,
        "access_allowed": true
    },
    "user": {
        "id": 12,
        "name": "Store Manager",
        "email": "manager@acme.test",
        "is_tenant_admin": false,
        "belongs_to_main_branch": false,
        "in_main_branch": false,
        "active_membership_count": 2,
        "capabilities": {
            "is_tenant_admin": false,
            "can_switch_branch": true,
            "can_switch_organization": false,
            "can_manage_billing": false
        }
    },
    "tenant": {
        "id": 1,
        "code": "TENANT-000001",
        "name": "Acme Store",
        "tenant_type": "organization",
        "status": "active"
    },
    "hierarchy": {
        "active_organization": {
            "id": 1,
            "parent_organization_id": null,
            "code": "ORG-000001",
            "name": "Acme Holdings",
            "currency": "NPR",
            "timezone": "Asia/Kathmandu",
            "status": "active"
        },
        "active_branch": {
            "id": 2,
            "organization_id": 1,
            "parent_branch_id": null,
            "code": "BRN-000002",
            "name": "Pokhara Branch",
            "is_main": false,
            "status": "active"
        },
        "active_branch_source": "session",
        "assigned_branches": ["..."],
        "organizations": ["..."]
    },
    "entitlements": { "api_access": true },
    "usage": { "branches": { "used": 2, "limit": 20 } }
}

3. Saas::database()->forBranch('BRN-000001')->healthCheck() & inspect()

// healthCheck()
{
    "healthy": true,
    "status": "healthy",
    "latency_ms": 2,
    "database_name": "org_1_branch_1",
    "server": { "id": 1, "code": "SRV-000001", "name": "Primary MySQL", "driver": "mysql" },
    "table_count": 14,
    "size_bytes": 245760,
    "error": null
}

// inspect()
{
    "context": { "owner_type": "branch", "owner_code": "BRN-000001", "effective_mode": "dedicated", "database_name": "org_1_branch_1" },
    "masked_dsn": "mysql://db_user:***@127.0.0.1:3306/org_1_branch_1",
    "tables": [{ "name": "orders", "rows": 1420 }, { "name": "users", "rows": 8 }],
    "size_bytes": 245760,
    "pending_migrations": [],
    "recent_operations": ["..."]
}

4. TenantDB::transfer(...)->upsertBy(['sku']) & TenantDB::compareSchema(...)

// transfer(...)->upsertBy(['sku'])
{
    "read": 120,
    "written": 120,
    "chunks": 1,
    "dry_run": false,
    "source": "tenant:TENANT-000001",
    "target": "branch:BRN-000001",
    "table": "catalog_items"
}

// compareSchema(['tenant', $tenant], ['branch', $branch], 'catalog_items')
{
    "source": "tenant:TENANT-000001",
    "target": "branch:BRN-000001",
    "table": "catalog_items",
    "source_exists": true,
    "target_exists": true,
    "only_in_source": ["cost_price"],
    "only_in_target": [],
    "in_both": ["id", "sku", "title", "price"]
}

5. Branch Access & User Membership Examples

Assign Branches to a User

// Assign 1 branch
Saas::organizations()->assignMembership(
    userId: $user->id,
    organizationId: $branch->organization_id,
    branchId: $branch->id,
    isTenantAdmin: false,
);

// Assign multiple branches (e.g. 2 branches)
foreach ([$kathmanduBranch, $pokharaBranch] as $branch) {
    Saas::organizations()->assignMembership($user->id, $branch->organization_id, $branch->id);
}

// Or grant tenant-wide admin access across all branches
Saas::organizations()->assignMembership($admin->id, isTenantAdmin: true);

Enforce & Scope in Your App

Saas::user()->branchCount();                  // 1, 2, ...
Saas::user()->assignedBranches();             // Collection of allowed branches
Saas::user()->currentBranch();                // Active branch
Saas::user()->hasBranchAccess('BRN-000002');  // true/false
Saas::user()->switchBranch('BRN-000002');     // Persists in session

// Scope queries to active branch or all assigned branches:
$orders = Order::where('branch_id', Saas::user()->currentBranch()?->id())->get();
$orders = Order::whereIn('branch_id', Saas::user()->assignedBranchIds())->get();

5a. Inter-Database Data Access (TenantDB / Saas::db()), Model Traits & Global Helpers

Scoped Connections & Simultaneous Multi-DB Queries

Each TenantDB::central(), TenantDB::tenant(...), TenantDB::branch(...), and TenantDB::client(...) call returns a ScopedDatabaseHandle using a dedicated connection name so querying across Central, Tenant, multiple Branches, and Clients in the same request never overwrites the active default connection:

use Ghimire\SaaS\Facades\TenantDB;

// Query Central, Tenant, multiple Branches & Clients simultaneously
$user    = TenantDB::central()->table('users')->find($userId);
$catalog = TenantDB::tenant('TENANT-000001')->table('catalog_items')->get();
$ktmSum  = TenantDB::branch('BRN-000001')->table('orders')->sum('total');
$pkrSum  = TenantDB::branch('BRN-000002')->table('orders')->sum('total');
$tickets = TenantDB::client('CLT-000001')->model(PosTicket::class)->latest()->limit(10)->get();

N+1-Free Cross-Database Relation Hydration (hydrate / hydrateFrom)

Attach related records from another database (or separate DB server) in one batched WHERE IN query:

$orders = TenantDB::branch('BRN-000001')->model(BranchOrder::class)->paginate(25);

// Hydrates `cashier` from Central DB and `product` from Tenant DB cleanly
TenantDB::hydrate($orders, 'central', User::class, 'cashier_id', 'cashier');
BranchOrder::hydrateFrom($orders, 'tenant', 'catalog_items', 'item_sku', 'product', 'sku');

Cross-Branch / Cross-Client Aggregation, Transfers, Multi-DB Transactions & Schema Diffs

// 1. Fan-out & aggregate across all active Branches or Clients
$byBranch   = TenantDB::acrossBranches($org, function ($db, $branch) {
    return $db->table('orders')->where('status', 'paid')->sum('total');
});
$grandTotal = TenantDB::sumAcross('branch', $org, 'orders', 'total', ['status' => 'paid']);
$orderCount = TenantDB::countAcross('client', $branch, 'pos_tickets');

// 2. Chunked cross-DB copy / upsert (supports Laravel 5.5-13+, dry-run & row mapping)
$summary = TenantDB::transfer(['tenant', $tenant], ['branch', $branch])
    ->table('catalog_items')
    ->where('is_active', true)
    ->orderBy('id')
    ->chunk(500)
    ->map(function (array $row) {
        $row['synced_at'] = now();
        return $row;
    })
    ->upsertBy(['sku']);

// 3. Coordinated multi-DB transaction (commits all, or rolls back all & logs on error)
TenantDB::transaction(['central', ['branch', $branch]], function ($handles) use ($branch) {
    $handles['central']->table('audit_notes')->insert(['note' => 'Settlement']);
    $handles['branch:' . $branch->code]->table('orders')->where('status', 'pending')->update(['status' => 'settled']);
});

// 4. Schema comparison between two databases
$diff = TenantDB::compareSchema(['tenant', $tenant], ['branch', $branch]);
$colDiff = TenantDB::compareSchema(['tenant', $tenant], ['branch', $branch], 'catalog_items');

Global Helper Functions (src/helpers.php)

Helper Function What It Returns / Does
tenant($key = null) Current TenantContract|null or attribute/metadata lookup
central(Closure $callback) Runs closure safely inside central context and restores prior tenancy state
current_organization() Active OrganizationContract|null in TenantContext
current_branch() Active BranchContract|null in TenantContext
current_client() Active ClientContract|null in TenantContext
saas_db($scope = null, $target = null) Returns InterDatabaseManager or a resolved ScopedDatabaseHandle (e.g. saas_db('branch', 'BRN-000001'))
in_tenant($tenant, Closure $callback) Temporarily switches into $tenant DB context and restores cleanly in finally
in_branch($branch, Closure $callback) Temporarily switches into $branch DB context and restores cleanly in finally
in_client($client, Closure $callback) Temporarily switches into $client DB context and restores cleanly in finally
tenant_asset($path, $tenant = null) Tenant-isolated public asset URL via TenantAssetController
global_asset($path) Application-level (central) asset URL bypassing tenant suffixes
saas_channel($channel, $hierarchy = false) Tenant/org/branch-prefixed broadcast channel name
saas_me($preset = null, $opts = []) Complete all-in-one host user SaaS context payload
saas_user_context($preset = null, $opts = []) Fluent UserContextService builder or resolved payload

Model Connection & Cross-Database Traits (Ghimire\SaaS\Traits\*)

Trait Purpose
ResolvesCentralConnection Pins central models to the central DB connection even inside a tenant/branch request
UsesTenantConnection Routes Eloquent queries to the active tenant connection
UsesBranchConnection Routes Eloquent queries to the active hierarchical branch connection
UsesClientConnection Routes Eloquent queries to the active hierarchical client connection
InteractsAcrossDatabases Adds belongsToCentralModel(), belongsToScopeModel(), and static hydrateFrom() onto models
BelongsToTenant / BelongsToHierarchy / BelongsToClient Automatic single-DB / logical isolation scoping by tenant_id, organization_id/branch_id, and client_id
HasCentralAuditable Tracks created_by, updated_by, and deleted_by on central models
SyncableResource Cross-tenant model synchronization support
use Ghimire\SaaS\Traits\InteractsAcrossDatabases;
use Ghimire\SaaS\Traits\UsesBranchConnection;
use Illuminate\Database\Eloquent\Model;

class BranchOrder extends Model
{
    use UsesBranchConnection;
    use InteractsAcrossDatabases;

    public function cashier()
    {
        return $this->belongsToCentralModel(\App\Models\User::class, 'cashier_id');
    }
}

6. Artisan CLI Commands

# Create tenant with org, branches, domains, plan, coupon, and trial
php artisan ghimire:tenant:build "Acme Store" \
  --type=organization \
  --org="Acme Holdings" \
  --branch="HQ:Kathmandu" \
  --domain="acme.local" \
  --domain="shop.acme.local" \
  --plan=PRO_PLAN \
  --period=monthly \
  --coupon=WELCOME20 \
  --trial=14

# Update, suspend, activate, or delete a tenant
php artisan ghimire:tenant:build "Acme V2" --action=update --tenant=TENANT-000001 --domain="vip.acme.local" --migrate --seed
php artisan ghimire:tenant:build --action=suspend --tenant=TENANT-000001
php artisan ghimire:tenant:build --action=activate --tenant=TENANT-000001
php artisan ghimire:tenant:build --action=delete --tenant=TENANT-000001 --drop-db

# Operations & maintenance
php artisan ghimire:tenant:list
php artisan ghimire:tenant:migrate
php artisan ghimire:tenant:backup
php artisan ghimire:tenant:restore
php artisan ghimire:domain:verify
php artisan ghimire:billing:renew
php artisan ghimire:saas:create-user
php artisan saas:sync-hierarchy
php artisan ghimire:doctor
php artisan ghimire:status

7. Queues (Supervisor) & Cron Jobs

  • Supervisor (php artisan queue:work): Tenant context (ghimire_tenant_code) is automatically stamped onto queued jobs dispatched during a tenant request and automatically restored/cleaned up by SaaSServiceProvider.
  • Cron (php artisan schedule:run): Use Saas::tenants()->forEachActiveTenant(fn ($tenant) => ...) for custom scheduled tasks that run across all active tenants.

8. Package Frontend Development (Contributors Only)

Client apps do not need to run npm — resources/dist/ is prebuilt. To rebuild the Developer Center UI from inside the package:

npm install
npm run build

License

MIT