laravel-saas maintained by ghimire
ghimire/laravel-saas
All-in-one modular Laravel 8–13 multi-tenant SaaS engine (PHP 8.1+), including isolated tenant databases, central organizations & branches, domain routing, subscriptions, coupons, billing & invoicing, entitlements, usage quotas, audit logging, encrypted backups, Saas facade + fluent provisioning, 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:
^8.1(8.1, 8.2, 8.3, 8.4+) - Laravel:
^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0 | ^13.0 - 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
Setting
SESSION_DOMAIN=nullkeeps cookies host-only so logging intostore1.localnever affectsstore2.local.
Step 3: Register Tenant Domain Middleware (One Line — Web & API)
Prepend ResolveTenantByDomainMiddleware globally so tenant database resolution runs before StartSession for 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\Domain\Http\Middleware\ResolveTenantByDomainMiddleware::class);
})
Laravel 8, 9 & 10 (app/Http/Kernel.php):
protected $middleware = [
\Ghimire\SaaS\Domain\Http\Middleware\ResolveTenantByDomainMiddleware::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\\DeveloperCenter\\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 Works
- Central Database: Stores
tenants,domains,organizations,branches,user_memberships,plans,plan_prices,saas_coupons,subscriptions,invoices,saas_payments,central_settings,audit_logs,backup_records,saas_users, and frameworksessions/cache/jobs. - Tenant Databases (
myapp_tenant_N): Contains only your client app's own tables (users,products,orders, etc.) — zero extraorganizations,branches, oruser_membershipstables polluting your tenant schema. - Auto-Migrate & Auto-Seed: Creating a tenant automatically creates its isolated database, runs all migrations in
database/migrations/(plus module tenant migrations), and runsTenantDatabaseSeeder+ your app'sDatabase\Seeders\DatabaseSeeder.
3. One-Call Fluent Provisioning (Saas::provision & Saas::forTenant)
Facade: Ghimire\SaaS\Core\Facades\Saas
Create a Tenant (One Call)
use Ghimire\SaaS\Core\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. Saas Facade & Service Classes Reference
| Facade Method | Underlying Service Class | Purpose |
|---|---|---|
Saas::provision() / Saas::forTenant() |
Ghimire\SaaS\Provisioning\TenantProvisioner |
Fluent create, update, suspend, activate, delete |
Saas::tenants() / Saas::tenancy() |
Ghimire\SaaS\Tenancy\Services\TenantManager |
runFor(), forEachActiveTenant(), migrate(), seed() |
Saas::context() |
Ghimire\SaaS\Tenancy\Services\TenantContext |
Current tenant, organization, and branch |
Saas::domains() |
Ghimire\SaaS\Domain\Services\DomainService |
Register, verify, normalize, resolve domains |
Saas::organizations() |
Ghimire\SaaS\Organization\Services\OrganizationService |
Manage central organizations & assignMembership() |
Saas::branches() |
Ghimire\SaaS\Branch\Services\BranchService |
Manage central branches & main branch |
Saas::user() |
Ghimire\SaaS\Organization\Services\UserAccessHelper |
User branch access, switching, main-branch checks |
Saas::subscriptions() |
Ghimire\SaaS\Subscription\Services\SubscriptionService |
Subscribe, proration, cancel, extend trial |
Saas::billing() |
Ghimire\SaaS\Billing\Services\BillingService |
Draft/issue invoices, payments, credit notes |
Saas::entitlements() |
Ghimire\SaaS\Entitlement\Services\EntitlementService |
Plan feature & limit checks |
Saas::usage() |
Ghimire\SaaS\Usage\Services\UsageService |
Usage tracking & quota enforcement |
Saas::settings() |
Ghimire\SaaS\Settings\Services\SettingsManager |
Cascading settings (branch -> org -> tenant -> central) |
Saas::centralSettings() |
Ghimire\SaaS\Settings\Services\CentralSettingsService |
Central defaults (e.g. defaultCurrency()) |
Saas::files() |
Ghimire\SaaS\Core\Storage\FileManager |
Tenant/org/branch-isolated storage |
Saas::health() |
Ghimire\SaaS\Core\Health\HealthCheckManager |
Environment & DB diagnostics |
Saas::packages() / Saas::modules() |
PackageRegistryContract / ModuleRegistryContract |
Registered packages & app modules |
Additional injectable services:
Ghimire\SaaS\Audit\Services\AuditLoggerGhimire\SaaS\Backup\Services\BackupManagerGhimire\SaaS\Payment\Services\PaymentGatewayManagerGhimire\SaaS\Billing\Services\TaxCalculator&PdfInvoiceGenerator
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();
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 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 byTenancyServiceProvider. - Cron (
php artisan schedule:run): UseSaas::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