Enterprise-grade Laravel multi-tenancy package built on stancl/tenancy with Livewire 3 integration, enhanced CLI tools, and comprehensive monitoring.

0.7.6.0 2025-08-25 15:46 UTC

README

Latest Version Total Downloads License

Enterprise-grade Laravel multi-tenancy built on top of stancl/tenancy

๐Ÿš€ Enhanced Multi-Tenancy - Extends stancl/tenancy with advanced features, enhanced CLI commands, performance monitoring, and universal routing capabilities.

โšก Quick Start

Installation

# Install the package (includes stancl/tenancy automatically)
composer require artflow-studio/tenancy

# Run the installation (sets up everything)
php artisan af-tenancy:install

# Test your setup
php artisan af-tenancy:test-all

# Create your first tenant
php artisan tenant:manage create

Basic Usage

// routes/web.php

// Central domain routes (your main app/admin)
Route::middleware(['central.web'])->group(function () {
    Route::get('/', [HomeController::class, 'index']);
    Route::get('admin', [AdminController::class, 'index']);
});

// Tenant routes (uses stancl/tenancy + our enhancements)
Route::middleware(['tenant.web'])->group(function () {
    Route::get('/', function () {
        $tenant = tenant(); // stancl/tenancy helper
        return "Welcome to {$tenant->name}!";
    });
    
    // Your tenant-specific routes here
    Route::resource('posts', PostController::class);
});

// Universal routes (work on both central and tenant domains)
Route::middleware(['universal.web'])->group(function () {
    Route::get('about', [AboutController::class, 'index']);
    Route::get('contact', [ContactController::class, 'index']);
});

โœจ Key Features

โœจ Key Features

Core Features (Built on stancl/tenancy)

  • ๐Ÿข Complete Database Isolation - Each tenant gets its own database using stancl/tenancy
  • ๐Ÿง  Universal Middleware - Routes that work on both central and tenant domains
  • ๐Ÿ  Homepage Management - Enable/disable tenant homepages with smart redirection
  • ๐ŸŒ Enhanced Domain Resolution - Built on stancl/tenancy's domain resolver
  • ๐Ÿ—„๏ธ Custom Database Names - User-defined database names with validation

Performance & Monitoring

  • ๐Ÿ“Š Real-time Monitoring - Built-in performance metrics and health checks
  • โšก High Performance - Optimized for 1000+ concurrent tenants (18ms avg response)
  • ๐Ÿงช Comprehensive Testing Suite - 15+ specialized testing commands with progress tracking
  • ๐Ÿ”ฅ Stress Testing - High-intensity load testing for production readiness
  • ๐Ÿ” System Validation - Automated health checks and repair tools

Developer Experience

  • ๐Ÿ”ง Zero Configuration - Works out of the box with sensible defaults
  • ๐Ÿ“ฑ Complete REST API - Full tenant management via API
  • โšก One-Command Setup - Install everything with php artisan af-tenancy:install
  • ๐Ÿ“š Comprehensive Documentation - Detailed guides and troubleshooting

Database Root Configuration

For automatic tenant database creation, you need MySQL root credentials:

# Add to your .env file
DB_ROOT_USERNAME=root
DB_ROOT_PASSWORD=your_mysql_root_password

Why Root Credentials?

  • Creates tenant databases automatically using stancl/tenancy
  • Grants proper MySQL privileges
  • Enables FastPanel integration
  • Ensures phpMyAdmin access

๐Ÿ“š Documentation

All documentation is organized in the docs/ folder:

Quick Links

๐Ÿ› ๏ธ Available Commands

Installation & Setup

php artisan af-tenancy:install          # Install and configure everything
php artisan af-tenancy:test-all         # Test your complete setup  
php artisan af-tenancy:check-routes     # Verify route configuration

Tenant Management

php artisan tenant:manage create        # Create new tenant (interactive)
php artisan tenant:manage list          # List all tenants
php artisan tenant:manage status        # Show tenant status
php artisan tenant:manage health        # Health check for tenants

Testing & Debugging

php artisan af-tenancy:test-database    # Test database connections
php artisan af-tenancy:test-auth        # Test authentication flow
php artisan af-tenancy:test-middleware  # Test middleware functionality
php artisan af-tenancy:debug-connection # Debug specific domain

Performance & Monitoring

php artisan tenancy:health              # System health check
php artisan tenancy:test-redis          # Test Redis configuration
php artisan af-tenancy:performance      # Performance benchmarks

๐Ÿš€ Built on stancl/tenancy

This package extends the excellent stancl/tenancy package. We use all of stancl/tenancy's core features:

  • Database Tenancy: Each tenant gets its own database
  • Domain Resolution: Automatic tenant identification by domain
  • Bootstrappers: Full stancl/tenancy bootstrapper support
  • Queue Isolation: Tenant-aware job queuing
  • Storage Isolation: Tenant-specific file storage

What We Add

  • Enhanced CLI commands with progress tracking
  • Advanced Redis multi-database support
  • Performance monitoring and testing tools
  • Universal routing capabilities
  • Homepage management features

๐Ÿค Contributing

Contributions are welcome! Please see our Contributing Guide for details.

๐Ÿ“„ License

The MIT License (MIT). Please see License File for more information.

๐Ÿ”— Links

Homepage Management

TENANT_HOMEPAGE_ENABLED=true TENANT_HOMEPAGE_AUTO_CREATE_DIR=true

Cache Configuration (Default: database)

TENANT_CACHE_DRIVER=database TENANT_CACHE_TTL=3600

API Security

TENANT_API_KEY=your-secure-api-key-here

Monitoring & Performance

TENANT_MONITORING_ENABLED=true


### Create Your First Tenant

```bash
php artisan tenant:manage create

The interactive prompts will guide you through:

  • Tenant name
  • Domain name
  • Custom database name (or auto-generate)
  • Homepage preference (enable/disable)

Verify Your Setup

# Quick system validation
php artisan tenancy:validate

# Test all tenant connections
php artisan tenancy:test-connections

# Performance benchmark
php artisan tenancy:test-performance-enhanced --skip-deep-tests

๐Ÿงช Comprehensive Testing Suite

Available Testing Commands

Command Purpose Recommended Use
tenancy:validate Complete system health check Daily development, deployment validation
tenancy:test-connections Database connection testing Daily in production, troubleshooting
tenancy:test-performance-enhanced Enhanced performance testing Weekly monitoring, after major changes
tenancy:test-isolation Data isolation validation After code changes, security audits
tenancy:stress-test High-intensity load testing Pre-production, capacity planning

Quick Testing Examples

# Daily health check (30 seconds)
php artisan tenancy:test-connections

# Performance test with your setup (45 seconds)
php artisan tenancy:test-performance-enhanced --concurrent-users=5 --skip-deep-tests

# Security validation (60 seconds)
php artisan tenancy:test-isolation --tenants=3 --operations=5

# Stress test for production readiness (5 minutes)
php artisan tenancy:stress-test --users=50 --duration=60 --tenants=5

Testing Results You Can Expect

โœ… Connection Success Rate: 100% (all tenants)
โœ… Average Response Time: <25ms (Excellent rating)
โœ… Database Creation: 100% success rate
โœ… Isolation Tests: All security validations passing
โœ… Stress Test: Production-ready performance confirmed

๐Ÿข Enhanced Tenant Creation

Interactive Tenant Creation Wizard

Create tenants with our enhanced interactive wizard:

php artisan tenant:create

Wizard Steps:

  1. Basic Information

    • Tenant name
    • Domain name
    • Custom database name (optional - auto-generated if empty)
    • Homepage preference
    • Tenant notes
  2. Creation Mode Selection

    • [0] Localhost: Development mode with local database creation
    • [1] FastPanel: Production mode with FastPanel integration
  3. Database User Configuration (FastPanel mode)

    • [0] No MySQL user needed: Database only
    • [1] Use existing MySQL user: Select from FastPanel users (Default)
    • [2] Create new MySQL user: Generate new user
  4. Automatic Setup

    • Database creation with proper privileges
    • Migration execution
    • Seeder execution (optional)
    • FastPanel integration (if selected)

Database Naming Features

Auto-Generated Names

  • Format: tenant_[UUID] (e.g., tenant_1a2b3c4d5e6f7g8h)
  • Unique and collision-free
  • Follows TENANT_DB_PREFIX configuration

Custom Names with Prefix

  • Input: mycompany โ†’ Database: tenant_mycompany
  • Automatic prefix application from TENANT_DB_PREFIX
  • Input validation and sanitization
  • Prevents duplicate names

Environment Integration

TENANT_DB_PREFIX=tenant_        # Applied to custom names
TENANT_DB_CHARSET=utf8mb4       # Database charset
TENANT_DB_COLLATION=utf8mb4_unicode_ci  # Database collation

FastPanel Mode Features

Automatic Privilege Management

  • Detects ENV root credentials automatically
  • Grants MySQL privileges to selected database users
  • Ensures phpMyAdmin auto-login compatibility
  • Creates proper database-user mappings

User Selection Options

Select database user for assignment:
[skip] โญ๏ธ  Skip database user assignment
[0   ] al_emaan_pk (ID: 15) - Owner: 1
[1   ] cafe_artflow (ID: 7) - Owner: 1
[2   ] dbadmin (ID: 1) - Owner: 2

Smart Defaults

  • ENV root credentials prioritized automatically
  • Existing users selected by default
  • Clear labeling with owner information
  • Fallback options for all scenarios

Command Line Options

Create with Options

php artisan tenant:create \
  --name="My Company" \
  --domain="mycompany.example.com" \
  --database="custom_db" \
  --homepage \
  --notes="Production tenant for My Company"

Batch Creation

# Create multiple test tenants
php artisan tenancy:create-test-tenants

# Create tenant with specific configuration
php artisan tenant:create --force --name="Test" --domain="test.local"

๐Ÿ  Homepage Management

AF-MultiTenancy includes smart homepage management:

  • Homepage Enabled: Tenant sees their homepage at root /
  • Homepage Disabled: Tenant is redirected to /login
  • Interactive Setup: Choose during tenant creation
  • Runtime Control: Toggle anytime without restart

CLI Management

# Enable homepage for a tenant
php artisan tenant:manage enable-homepage

# Disable homepage for a tenant
php artisan tenant:manage disable-homepage

API Management

# Enable homepage via API
POST /api/tenants/{id}/enable-homepage?api_key=your-key

# Disable homepage via API
POST /api/tenants/{id}/disable-homepage?api_key=your-key

๐Ÿ“š Documentation

๐Ÿ”ง Quick Commands

# Install package
php artisan af-tenancy:install

# Manage tenants
php artisan tenant:manage

# Check system health
php artisan tenancy:health

# Run performance tests
php artisan tenancy:test-performance

# Create test tenants
php artisan tenancy:create-test-tenants --count=3

๐ŸŽฏ What Makes It Special

Built for Developers

  • One-command installation with interactive setup
  • Intuitive CLI commands with helpful prompts
  • Clear documentation with practical examples
  • Laravel-native design patterns

Production Ready

  • 100% tenant isolation - No data leaks possible
  • High performance - Handles 100+ tenants efficiently
  • Real-time monitoring - Track performance and health
  • Secure by default - Production-ready security

Smart Features

  • Homepage management - Control tenant landing pages
  • Custom database names - Flexible naming with validation
  • Smart domain routing - Handles central and tenant domains
  • Automatic cleanup - No manual database management

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

๐Ÿ“„ License

This package is licensed under the MIT License.

๐Ÿ†˜ Support

AF-MultiTenancy - Making Laravel multi-tenancy simple, secure, and scalable.

API Usage

# Create tenant (X-API-Key required)
curl -X POST -H "X-API-Key: your-api-key" \
     -H "Content-Type: application/json" \
     -d '{"name":"Acme Corp","domain":"acme.example.com"}' \
     http://yourapp.com/api/tenancy/tenants

4. Access dashboard: http://your-domain.com/admin/tenants


### ๐ŸŽฏ Quick Test Setup

```bash
# Create 5 test tenants instantly
php artisan tenancy:create-test-tenants

# Test performance with concurrent users
php artisan tenancy:test-performance

๐Ÿ“‹ Requirements

  • PHP: 8.1+ (8.2+ recommended)
  • Laravel: 10.0+ or 11.0+
  • Database: MySQL 5.7+/8.0+ or PostgreSQL 13+
  • Cache: Redis (recommended for performance)

๏ฟฝ Key Features

๐Ÿ—๏ธ Built on stancl/tenancy

  • Multi-database architecture with tenant isolation
  • Domain-based tenant resolution
  • Queue job and cache isolation
  • File storage isolation
  • Tenant-aware Artisan commands

๐Ÿš€ Artflow Studio Enhancements

Performance & Enterprise

  • โœ… 80-95% faster tenant switching with persistent connections
  • โœ… Real-time monitoring dashboard with system metrics
  • โœ… Advanced admin dashboard with responsive UI
  • โœ… Complete REST API (50+ endpoints) for external integrations
  • โœ… Connection pooling for enterprise-scale concurrent users

Management & Security

  • โœ… Tenant status management (active, inactive, blocked)
  • โœ… API authentication (API keys, Bearer tokens)
  • โœ… Health monitoring and performance analytics
  • โœ… Comprehensive CLI tools (20+ Artisan commands)
  • โœ… Test data generation and performance testing

Developer Experience

  • โœ… Zero configuration setup - works out of the box
  • โœ… Interactive installer with guided setup
  • โœ… Debug dashboard with real-time debugging
  • โœ… Load testing tools built-in
  • โœ… Minimal app pollution - configs stay in package

๐Ÿ–ฅ๏ธ FastPanel Integration

  • โœ… Automatic database creation - Seamless FastPanel CLI integration
  • โœ… Database user assignment - Automatic MySQL user mapping
  • โœ… Privilege management - Auto-grant database access permissions
  • โœ… Panel owner assignment - Link databases to FastPanel users
  • โœ… phpMyAdmin compatibility - Full auto-login support
  • โœ… ENV root credential detection - Automatic privilege escalation
  • โœ… Smart user selection - Default to existing users with fallback options
  • โœ… Database prefix support - Respects TENANT_DB_PREFIX configuration

๏ฟฝ Real-Time Monitoring & Analytics

๐Ÿ”ฅ New in v0.4.6: Enterprise-Grade Real-Time Monitoring

Monitor your entire multi-tenant ecosystem with comprehensive real-time analytics and performance tracking.

System Monitoring Dashboard

# Access the real-time monitoring dashboard
# URL: /admin/monitoring/dashboard

Live Metrics Available:

  • ๐Ÿ–ฅ๏ธ System Stats: CPU, memory, disk usage, PHP version, Laravel version
  • ๐Ÿ—„๏ธ Database Analytics: Connection pools, query performance, slow queries
  • ๐Ÿข Tenant Overview: Active/blocked tenants, recently accessed, growth metrics
  • ๐Ÿ”— Connection Monitoring: Active connections, connection pool status, DB load
  • โšก Performance Metrics: Response times, cache hit ratios, query optimization
  • ๐Ÿ“ˆ Resource Usage: Memory per tenant, disk space, bandwidth usage

Real-Time API Endpoints

# Get comprehensive system statistics
GET /admin/monitoring/system-stats

# Get real-time tenant statistics
GET /admin/monitoring/tenant-stats/{tenantId?}

# Monitor database connections live
GET /admin/monitoring/connections

# Get dashboard overview data
GET /admin/monitoring/dashboard

# Clear monitoring caches
DELETE /admin/monitoring/clear-caches

CLI Monitoring Commands

# Real-time system monitoring (live updates)
php artisan tenancy:monitor --live

# Get comprehensive health check
php artisan tenancy:health --detailed

# Performance benchmarking
php artisan tenancy:test-performance --concurrent=50

# Generate detailed performance reports
php artisan tenancy:report --format=json --interval=24h

Example: Real-Time Dashboard Data

{
  "success": true,
  "data": {
    "summary": {
      "total_tenants": 145,
      "active_tenants": 142,
      "blocked_tenants": 3,
      "total_databases": 145,
      "total_connections": 23,
      "memory_usage": "2.4GB",
      "uptime": "15 days"
    },
    "performance": {
      "avg_response_time": "45ms",
      "queries_per_second": 1247,
      "cache_hit_ratio": 94.2,
      "database_performance": "optimal"
    },
    "recent_activity": {
      "new_tenants_today": 5,
      "recently_accessed": 67,
      "peak_concurrent_users": 89
    }
  },
  "timestamp": "2024-08-01T15:30:45Z"
}

Automated Alerts & Notifications

๐Ÿš€ Quick Usage

Basic Tenant Management

# Create a tenant
php artisan tenant:manage create "Company Name" company.example.com

# List tenants  
php artisan tenant:manage list

# Get tenant status
php artisan tenant:manage status {tenant-id}

# Update tenant status
php artisan tenant:manage status {tenant-id} --status=active

Environment Configuration

# Required API key
TENANT_API_KEY=sk_tenant_live_your_secure_api_key_here

# Performance (recommended)
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1

Admin Dashboard

  • URL: http://your-domain.com/admin/tenants
  • Real-time Monitoring: http://your-domain.com/admin/monitoring/dashboard
  • API Endpoints: See API.md for complete documentation
  • CLI Commands: See COMMANDS.md for all available commands

๐Ÿ—๏ธ Architecture

Database Structure

The package uses stancl/tenancy at its core:

  • Central Database: Stores tenant information (tenants and domains tables)
  • Tenant Databases: Separate database per tenant (automatically managed)
  • No App Pollution: Configs and migrations stay in the package directory

How Tenant Databases Work

// stancl/tenancy automatically manages tenant databases
// Database names: tenant_{tenant_id}
// Example: tenant_9c8e2fcf-9999-4999-9999-123456789abc

// The package handles:
// โœ… Database creation/deletion
// โœ… Connection switching  
// โœ… Migration management
// โœ… Data isolation

Configuration Files

  • config/tenancy.php - stancl/tenancy core configuration (published)
  • config/artflow-tenancy.php - Artflow enhancements (published)
  • Package configs remain internal (no app pollution)

๐Ÿ“Š Performance

Benchmarks

  • 80-95% faster tenant switching vs standard implementations
  • Persistent connections for enterprise-scale concurrent users
  • Memory optimized with intelligent resource management
  • 500+ concurrent users supported

Real-Time Monitoring

  • System resource tracking (CPU, memory, connections)
  • Tenant performance analytics
  • Database health monitoring
  • Automatic alerting and notifications

๐Ÿ“š Documentation

  • COMMANDS.md - Complete CLI reference with all available commands
  • API.md - Full REST API documentation with examples
  • ROADMAP.md - Development roadmap and upcoming features

๐Ÿ”ง Advanced Configuration

Publishing Package Files (Optional)

# Publish configs only (recommended)
php artisan vendor:publish --tag=tenancy-config

# Publish migrations for customization
php artisan vendor:publish --tag=tenancy-migrations

# Publish views for admin dashboard customization
php artisan vendor:publish --tag=tenancy-views

# Publish routes for customization
php artisan vendor:publish --tag=tenancy-routes

Cache Configuration

// config/artflow-tenancy.php
'cache' => [
    'ttl' => 3600,
    'prefix' => 'tenant_',
    'driver' => 'redis', // Use Redis for performance
],

๐Ÿšจ Troubleshooting

Common Issues

Commands not found:

php artisan config:clear
php artisan cache:clear
composer dump-autoload

Database connection issues:

# Check tenant database status
php artisan tenant:manage status {tenant-id}

# Test tenant connections
php artisan tenant:manage health

Performance issues:

# Clear all caches
php artisan tenancy:clear-cache

# Test performance
php artisan tenancy:test-performance

๐Ÿ” Security

  • Tenant Isolation: Complete database, cache, and file isolation
  • API Authentication: API keys and Bearer tokens supported
  • Rate Limiting: Configurable per-endpoint rate limits
  • Secure Connections: SSL/TLS support for all tenant domains

๐Ÿค Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This package is open-sourced software licensed under the MIT license.

๐Ÿ™ Credits

๐Ÿ“ž Support

๐Ÿš€ Ready to scale your multi-tenant Laravel application? Install now and get started in minutes! repository: your-app/tenancy tag: latest

service: type: LoadBalancer port: 80

ingress: enabled: true hosts: - host: "*.your-domain.com" paths: ["/"]

mysql: enabled: true auth: rootPassword: your_password

redis: enabled: true


---

## ๐Ÿ“Š Performance Monitoring

### Built-in Monitoring Commands

```bash
# Real-time performance monitoring
php artisan tenancy:monitor --live

# Health check with alerts
php artisan tenancy:health --alert-email=admin@your-app.com

# Generate performance reports
php artisan tenancy:report --format=json --output=/path/to/reports/

# Monitor specific metrics
php artisan tenancy:stats --metric=response_time --interval=5m

Integration with APM Tools

New Relic Integration

// In AppServiceProvider
public function boot()
{
    if (class_exists(\NewRelic\Agent::class)) {
        Event::listen('tenancy.initialized', function ($tenant) {
            \NewRelic\Agent::addCustomAttribute('tenant_id', $tenant->uuid);
            \NewRelic\Agent::addCustomAttribute('tenant_name', $tenant->name);
        });
    }
}

DataDog Integration

// Custom middleware for DataDog metrics
class TenancyDataDogMiddleware
{
    public function handle($request, Closure $next)
    {
        $start = microtime(true);
        
        $response = $next($request);
        
        $duration = microtime(true) - $start;
        
        DataDog::increment('tenancy.request.count', 1, [
            'tenant' => tenant()?->uuid ?? 'central',
            'status' => $response->getStatusCode()
        ]);
        
        DataDog::histogram('tenancy.request.duration', $duration * 1000, [
            'tenant' => tenant()?->uuid ?? 'central'
        ]);
        
        return $response;
    }
}

๐Ÿ”ง Advanced Customization

Custom Tenant Model

<?php

namespace App\Models;

use ArtflowStudio\Tenancy\Models\Tenant as BaseTenant;

class Tenant extends BaseTenant
{
    /**
     * Additional fillable attributes
     */
    protected $fillable = [
        ...parent::$fillable,
        'subscription_plan',
        'billing_email',
        'custom_settings'
    ];

    /**
     * Custom relationships
     */
    public function subscription()
    {
        return $this->belongsTo(Subscription::class);
    }

    /**
     * Custom business logic
     */
    public function isSubscriptionActive(): bool
    {
        return $this->subscription && $this->subscription->isActive();
    }
}

Custom Middleware

<?php

namespace App\Http\Middleware;

use Closure;
use ArtflowStudio\Tenancy\Http\Middleware\TenantMiddleware as BaseTenantMiddleware;

class CustomTenantMiddleware extends BaseTenantMiddleware
{
    public function handle($request, Closure $next)
    {
        // Run base tenant middleware
        $response = parent::handle($request, $next);
        
        // Add custom logic
        if (tenant() && !tenant()->isSubscriptionActive()) {
            return response()->view('subscription.expired', ['tenant' => tenant()], 402);
        }
        
        return $response;
    }
}

Custom Service Provider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use ArtflowStudio\Tenancy\Services\TenantService;

class CustomTenancyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Override default tenant service
        $this->app->singleton(TenantService::class, function ($app) {
            return new CustomTenantService();
        });
        
        // Add custom event listeners
        Event::listen('tenancy.tenant.created', function ($tenant) {
            // Send welcome email
            // Create default settings
            // Setup billing
        });
    }
}

๐Ÿค Contributing

We welcome contributions from the community! Here's how you can help:

Development Setup

# Clone the repository
git clone https://github.com/artflow-studio/tenancy.git
cd tenancy

# Install dependencies
composer install

# Run tests
./vendor/bin/phpunit

# Run performance tests
php artisan tenancy:test-performance --dev

Contribution Guidelines

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Write tests for your changes
  4. Ensure all tests pass
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Code Standards

  • Follow PSR-12 coding standards
  • Write comprehensive tests
  • Document new features
  • Update CHANGELOG.md

๐Ÿ“ž Support & Community

Documentation & Resources

Community Support

Professional Support

  • ๐Ÿข Enterprise Support: Contact Sales
  • ๐Ÿš€ Migration Services: Professional migration from other tenancy packages
  • โšก Performance Optimization: Custom performance tuning services
  • ๐Ÿ”ง Custom Development: Tailored features for enterprise needs

Learning Resources

๐Ÿ“„ License

This package is open-sourced software licensed under the MIT license.

๐Ÿ† Sponsors & Credits

Built With

Special Thanks

  • Samuel ล tancl - Creator of stancl/tenancy package
  • Taylor Otwell - Creator of Laravel Framework
  • The Laravel Community - For continuous inspiration and support

Become a Sponsor

Support the development of this package:

๐ŸŒŸ Star History

Star History Chart

Made with โค๏ธ by Artflow Studio

Empowering developers to build scalable multi-tenant applications with ease

Follow on Twitter Join Discord Subscribe on YouTube

| `/tenancy/clear-all-caches` | POST | Clear all caches | None | | `/tenancy/system-info` | GET | System information | None | | `/tenancy/maintenance/on` | POST | Enable maintenance mode | `message: string (optional)` | | `/tenancy/maintenance/off` | POST | Disable maintenance mode | None |

Backup & Restore

Endpoint Method Purpose Parameters
/tenancy/tenants/{uuid}/backup POST Backup tenant database include_data: boolean, compression: boolean
/tenancy/tenants/{uuid}/restore POST Restore tenant from backup backup_file: file, confirm: true
/tenancy/tenants/{uuid}/export POST Export tenant data format: json|csv|sql, tables: []
/tenancy/import-tenant POST Import tenant data import_file: file, name: string, domain: string

Analytics & Reports

Endpoint Method Purpose Parameters
/tenancy/analytics/overview GET Analytics overview period: day|week|month|year
/tenancy/analytics/usage GET Usage analytics tenant_uuid: string (optional)
/tenancy/analytics/performance GET Performance analytics metric: cpu|memory|disk|queries
/tenancy/analytics/growth GET Growth analytics period: day|week|month|year
/tenancy/reports/tenants GET Tenants report format: json|csv|pdf, filters: {}
/tenancy/reports/system GET System report format: json|csv|pdf, sections: []

Webhooks

Endpoint Method Purpose Parameters
/tenancy/webhooks/tenant-created POST Tenant creation webhook Webhook payload
/tenancy/webhooks/tenant-updated POST Tenant update webhook Webhook payload
/tenancy/webhooks/tenant-deleted POST Tenant deletion webhook Webhook payload

๐Ÿ› ๏ธ Artisan Commands Reference

Primary Tenant Management Command

The package provides a comprehensive tenant:manage command with multiple actions:

php artisan tenant:manage {action} [options]

Available Actions

Command Purpose
tenant:manage create Create new tenant interactively
tenant:manage list List all tenants in table format
tenant:manage delete Delete tenant and database
tenant:manage activate Activate suspended tenant
tenant:manage deactivate Deactivate active tenant
tenant:manage migrate Run migrations for specific tenant
tenant:manage migrate-all Run migrations for all tenants
tenant:manage seed Seed specific tenant database
tenant:manage seed-all Seed all tenant databases
tenant:manage status Show detailed tenant status
tenant:manage health Check system health

Command Options

Option Description
--tenant=UUID Target specific tenant by UUID
--name=NAME Set tenant name (create)
--domain=DOMAIN Set tenant domain (create)
--database=NAME Custom database name (create)
--status=STATUS Set tenant status (create)
--notes=TEXT Add tenant notes (create)
--force Skip confirmation prompts
--seed Run seeders after migration
--fresh Drop tables before migrating

Usage Examples

# Create new tenant
php artisan tenant:manage create --name="Acme Corp" --domain="acme.local"

# List all tenants
php artisan tenant:manage list

# Migrate specific tenant
php artisan tenant:manage migrate --tenant=abc-123-def

# Migrate all tenants with fresh install
php artisan tenant:manage migrate-all --fresh --seed

# Check tenant status
php artisan tenant:manage status --tenant=abc-123-def

# System health check
php artisan tenant:manage health

# Delete tenant (with confirmation)
php artisan tenant:manage delete --tenant=abc-123-def

# Force delete without confirmation
php artisan tenant:manage delete --tenant=abc-123-def --force

๐Ÿ—๏ธ How It Extends stancl/tenancy

This package builds upon stancl/tenancy by adding:

Enhanced Models

// Our enhanced Tenant model vs stancl/tenancy
ArtflowStudio\Tenancy\Models\Tenant extends Stancl\Tenancy\Database\Models\Tenant

Additional Features:

  • Status management (active, suspended, blocked, inactive)
  • Enhanced domain relationships
  • Database size tracking
  • Migration status monitoring
  • User activity tracking

Custom Middleware

// Our unified middleware vs stancl/tenancy's separate middleware
'tenant' => ArtflowStudio\Tenancy\Http\Middleware\TenantMiddleware::class

Enhanced Features:

  • Combined tenant identification and database switching
  • Status-based access control (blocks suspended/inactive tenants)
  • Error page rendering for blocked tenants
  • Performance optimizations

Advanced Services

// Our TenantService extends functionality
ArtflowStudio\Tenancy\Services\TenantService

Additional Capabilities:

  • Bulk operations (migrate all, clear caches)
  • Advanced monitoring and statistics
  • Database management (create, migrate, seed, reset)
  • Performance metrics collection

Admin Interface

What stancl/tenancy doesn't provide:

  • Complete admin dashboard
  • Visual tenant management
  • Real-time monitoring
  • Migration control interface
  • API endpoints for external access

๐ŸŽ›๏ธ Package Structure

packages/artflow-studio/tenancy/
โ”œโ”€โ”€ ๐Ÿ“ config/
โ”‚   โ””โ”€โ”€ tenancy.php              # Enhanced tenancy configuration
โ”œโ”€โ”€ ๐Ÿ“ database/
โ”‚   โ””โ”€โ”€ migrations/
โ”‚       โ”œโ”€โ”€ create_tenants_table.php
โ”‚       โ””โ”€โ”€ create_domains_table.php
โ”œโ”€โ”€ ๐Ÿ“ resources/
โ”‚   โ””โ”€โ”€ views/
โ”‚       โ”œโ”€โ”€ admin/
โ”‚       โ”‚   โ”œโ”€โ”€ dashboard.blade.php    # Main admin dashboard
โ”‚       โ”‚   โ”œโ”€โ”€ create.blade.php       # Create tenant form
โ”‚       โ”‚   โ””โ”€โ”€ show.blade.php         # Tenant details
โ”‚       โ”œโ”€โ”€ errors/
โ”‚       โ”‚   โ”œโ”€โ”€ tenant-blocked.blade.php
โ”‚       โ”‚   โ”œโ”€โ”€ tenant-suspended.blade.php
โ”‚       โ”‚   โ””โ”€โ”€ tenant-inactive.blade.php
โ”‚       โ””โ”€โ”€ layouts/
โ”œโ”€โ”€ ๐Ÿ“ routes/
โ”‚   โ””โ”€โ”€ tenancy.php              # All package routes
โ”œโ”€โ”€ ๐Ÿ“ src/
โ”‚   โ”œโ”€โ”€ ๐Ÿ“ Commands/
โ”‚   โ”‚   โ””โ”€โ”€ TenantCommand.php    # Enhanced tenant management
โ”‚   โ”œโ”€โ”€ ๐Ÿ“ Http/
โ”‚   โ”‚   โ”œโ”€โ”€ Controllers/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ TenantApiController.php    # API endpoints
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ TenantViewController.php   # Web interface
โ”‚   โ”‚   โ””โ”€โ”€ Middleware/
โ”‚   โ”‚       โ””โ”€โ”€ TenantMiddleware.php       # Unified tenancy middleware
โ”‚   โ”œโ”€โ”€ ๐Ÿ“ Models/
โ”‚   โ”‚   โ”œโ”€โ”€ Tenant.php           # Enhanced tenant model
โ”‚   โ”‚   โ””โ”€โ”€ Domain.php           # Enhanced domain model
โ”‚   โ”œโ”€โ”€ ๐Ÿ“ Services/
โ”‚   โ”‚   โ””โ”€โ”€ TenantService.php    # Core business logic
โ”‚   โ””โ”€โ”€ TenancyServiceProvider.php       # Auto-discovery provider
โ”œโ”€โ”€ composer.json                # Package definition
โ””โ”€โ”€ README.md                   # This documentation

๐ŸŽฎ Usage Examples

Creating Tenants

Via Admin Dashboard

  1. Navigate to /admin/dashboard
  2. Click "Create New Tenant"
  3. Fill the form and submit

Via API

curl -X POST "http://your-domain.com/tenancy/tenants/create" \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Acme Corporation",
    "domain": "acme.yourdomain.com",
    "status": "active",
    "run_migrations": true,
    "notes": "New enterprise client"
  }'

Via Artisan Command

php artisan tenant:create "Acme Corporation" acme.yourdomain.com --migrate

Managing Tenants

Tenant Status Management

// In your controller
use ArtflowStudio\Tenancy\Services\TenantService;

$tenantService = app(TenantService::class);

// Suspend a tenant
$tenantService->updateStatus($tenantUuid, 'suspended');

// Activate a tenant
$tenantService->updateStatus($tenantUuid, 'active');

// Block a tenant (shows error page)
$tenantService->updateStatus($tenantUuid, 'blocked');

Database Operations

// Migrate specific tenant
$tenantService->migrateTenant($tenantUuid);

// Seed tenant database
$tenantService->seedTenant($tenantUuid);

// Reset tenant database (DANGEROUS)
$tenantService->resetTenantDatabase($tenantUuid);

// Migrate all tenants
$tenantService->migrateAllTenants();

๐Ÿ”€ Routing & Middleware

Simple Tenant Middleware (tenant)

The package provides a simplified middleware that handles everything for tenant routes:

// In your routes/web.php - Simple and clean!
Route::middleware(['tenant'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/customers', [CustomerController::class, 'index']);
    Route::resource('orders', OrderController::class);
    // All your tenant routes here
});

What the tenant middleware does:

  • โœ… Initializes tenancy by domain
  • โœ… Validates domain access
  • โœ… Checks tenant status (active/inactive)
  • โœ… Shows professional error pages for inactive tenants
  • โœ… Handles all authentication context

Advanced Middleware Options

1. Smart Domain Resolver (smart.domain)

Automatically routes between central and tenant domains:

// In your routes/web.php - handles both central and tenant domains
Route::middleware(['web', 'smart.domain'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/profile', [ProfileController::class, 'show']);
    // These routes work on both central and tenant domains
});

2. Central Domain Only (central.tenant)

Restricts routes to central domain only:

// In your routes/api.php - central domain only
Route::middleware(['api', 'central.tenant'])->prefix('api')->group(function () {
    Route::get('/health', [HealthController::class, 'check']);
    Route::post('/admin/tenants', [AdminController::class, 'createTenant']);
    // Only accessible from central domains (127.0.0.1, localhost, APP_DOMAIN)
});

Tenant Status Validation

If your tenants table has a status column, the middleware automatically handles:

  • active - Normal operation โœ…
  • inactive - Shows professional error page ๐Ÿšซ
  • suspended - Shows suspension notice โš ๏ธ
  • maintenance - Shows maintenance message ๐Ÿ”ง

Using Tenant Middleware

// In your routes/web.php
Route::middleware(['tenant'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])
         ->name('tenant.dashboard');
    
    Route::resource('customers', CustomerController::class);
    Route::resource('orders', OrderController::class);
});

Legacy Compatibility

Old middleware names still work:

// These all point to the same simplified middleware
Route::middleware(['smart.tenant'])->group(function () { /* routes */ });
Route::middleware(['tenant.auth'])->group(function () { /* routes */ });

Tenant Context in Controllers

<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;

class DashboardController extends Controller
{
    public function index()
    {
        // Current tenant is automatically set by middleware
        $tenant = tenant();
        
        // All database queries now use tenant database
        $customers = \App\Models\Customer::all();
        $orders = \App\Models\Order::count();
        
        return view('tenant.dashboard', compact('tenant', 'customers', 'orders'));
    }
}

๐Ÿ”Œ API Reference

Authentication

All API endpoints require authentication via the X-API-Key header with proper middleware enforcement:

API Key Authentication (Required):

curl -X GET "http://your-domain.com/tenancy/tenants" \
  -H "X-API-Key: sk_tenant_live_your_secure_api_key_here"

Environment Variables:

# Required API key for production and development
TENANT_API_KEY=sk_tenant_live_your_secure_api_key_here

Security Features:

  • โœ… Middleware-enforced authentication - All API routes protected by tenancy.api middleware
  • โœ… Rate limiting - Built-in throttling via throttle:api
  • โœ… Development mode - Localhost allowed without API key if none configured
  • โœ… Production mode - API key always required in production environments
  • โœ… Consistent error responses - Standardized 401 responses for unauthorized access

Error Responses:

{
  "success": false,
  "error": "Unauthorized",
  "message": "Invalid or missing API key. Please include X-API-Key header.",
  "code": 401,
  "timestamp": "2025-08-01T14:30:00Z"
}

Security Notes:

  • API key validation happens at the middleware level before reaching controllers
  • No API key bypass in production environments
  • Development environments (localhost) can work without API key for testing
  • All routes under /tenancy/* are automatically protected

Tenant Management Endpoints

List Tenants

GET /tenancy/tenants

Query Parameters:

  • page (int): Page number for pagination (default: 1)
  • per_page (int): Items per page (default: 15, max: 100)
  • search (string): Search by tenant name or domain
  • status (string): Filter by status (active, suspended, blocked, inactive)
  • sort (string): Sort field (name, created_at, status)
  • order (string): Sort order (asc, desc)

Example Request:

GET /tenancy/tenants?page=1&per_page=20&search=acme&status=active&sort=created_at&order=desc

Response:

{
  "success": true,
  "data": {
    "data": [
      {
        "id": 1,
        "uuid": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Acme Corporation",
        "database_name": "tenant_acme_abc123",
        "status": "active",
        "domains": [
          {
            "id": 1,
            "domain": "acme.yourdomain.com",
            "tenant_id": 1
          }
        ],
        "created_at": "2025-01-01T00:00:00.000000Z",
        "updated_at": "2025-01-01T00:00:00.000000Z"
      }
    ],
    "current_page": 1,
    "per_page": 15,
    "total": 1
  },
  "timestamp": "2025-07-31T14:30:00Z"
}

Create Tenant

POST /tenancy/tenants/create

Request Body:

{
  "name": "Acme Corporation",
  "domain": "acme.yourdomain.com",
  "status": "active",
  "database_name": "custom_db_name",
  "notes": "Customer notes here",
  "run_migrations": true
}

Required Fields:

  • name (string): Tenant display name
  • domain (string): Primary domain for tenant

Optional Fields:

  • status (string): active|suspended|blocked|inactive (default: active)
  • database_name (string): Custom database name (auto-generated if not provided)
  • notes (string): Additional notes
  • run_migrations (boolean): Run migrations after creation (default: false)

Response:

{
  "success": true,
  "data": {
    "tenant": {
      "id": 1,
      "uuid": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Acme Corporation",
      "database_name": "tenant_acme_abc123",
      "status": "active"
    },
    "domain": {
      "id": 1,
      "domain": "acme.yourdomain.com",
      "tenant_id": 1
    },
    "migration_status": "completed"
  },
  "message": "Tenant created successfully",
  "timestamp": "2025-07-31T14:30:00Z"
}

Get Tenant Details

GET /tenancy/tenants/{uuid}

Update Tenant

PUT /tenancy/tenants/{uuid}

Delete Tenant

DELETE /tenancy/tenants/{uuid}

Update Tenant Status

PUT /tenancy/tenants/{uuid}/status

Request Body:

{
  "status": "suspended",
  "reason": "Payment overdue",
  "notify": true
}

Available Statuses:

  • active: Tenant fully operational
  • suspended: Temporary access restriction
  • blocked: Permanent access restriction
  • inactive: Tenant disabled but data preserved

Add Domain to Tenant

POST /tenancy/tenants/{uuid}/domains/create

Request Body:

{
  "domain": "subdomain.yourdomain.com",
  "is_primary": false,
  "ssl_enabled": true
}

Migrate Tenant Database

POST /tenancy/tenants/{uuid}/migrate

Request Body:

{
  "fresh": false,
  "seed": true,
  "timeout": 300
}

Database Management Endpoints

Migrate Tenant Database

POST /tenancy/tenants/{uuid}/migrate

Seed Tenant Database

POST /tenancy/tenants/{uuid}/seed

Reset Tenant Database

POST /tenancy/tenants/{uuid}/reset

โš ๏ธ Warning: This will delete all data in the tenant database.

System Endpoints

System Statistics

GET /tenancy/stats

Response:

{
  "success": true,
  "data": {
    "total_tenants": 25,
    "active_tenants": 22,
    "suspended_tenants": 2,
    "blocked_tenants": 1,
    "total_domains": 28,
    "total_database_size_mb": 1024.5,
    "cache_keys": 1500,
    "system_uptime": "5 days, 3 hours"
  }
}

Migrate All Tenants

POST /tenancy/migrate-all

Clear All Caches

POST /tenancy/cache/clear-all

Live Statistics (Real-time)

GET /tenancy/live-stats

๐ŸŽจ Customization

Custom Views

Publish views to customize the admin interface:

php artisan vendor:publish --tag=tenancy-views

Views will be published to: resources/views/vendor/tenancy/

Custom Routes

Publish routes to modify endpoints:

php artisan vendor:publish --tag=tenancy-routes

Routes will be published to: routes/tenancy.php

Custom Configuration

The package automatically publishes configuration. Modify config/tenancy.php:

<?php

return [
    'tenant_model' => \ArtflowStudio\Tenancy\Models\Tenant::class,
    'domain_model' => \ArtflowStudio\Tenancy\Models\Domain::class,
    
    'database' => [
        'prefix' => 'tenant_',
        'suffix' => '_db',
        'connection' => 'tenant',
    ],
    
    'cache' => [
        'enabled' => true,
        'ttl' => 3600,
    ],
    
    'api' => [
        'rate_limit' => [
            'enabled' => true,
            'attempts' => 60,
            'decay' => 1,
        ],
    ],
];

Extending Models

<?php

namespace App\Models;

use ArtflowStudio\Tenancy\Models\Tenant as BaseTenant;

class Tenant extends BaseTenant
{
    protected $fillable = [
        'name',
        'status',
        'custom_field',  // Add your custom fields
    ];
    
    public function customRelation()
    {
        return $this->hasMany(CustomModel::class);
    }
}

Update configuration:

// config/tenancy.php
'tenant_model' => \App\Models\Tenant::class,

๐Ÿ”ง Performance Optimization

Redis Caching

// config/cache.php
'default' => env('CACHE_DRIVER', 'redis'),

Queue Configuration

For better performance with bulk operations:

# Start queue worker
php artisan queue:work redis --sleep=3 --tries=3 --timeout=60

๐Ÿšจ Troubleshooting

Common Issues

1. Package Not Auto-Discovered

# Clear composer cache and reinstall
composer clear-cache
composer install --optimize-autoloader

2. Config Not Auto-Published

# Manually publish config
php artisan vendor:publish --tag=tenancy-config

3. Migrations Not Running

# Check if migrations exist
php artisan migrate:status

# Run specific package migrations
php artisan migrate --path=vendor/artflow-studio/tenancy/database/migrations

4. Tenant Database Connection Failed

# Check tenant database config in .env
TENANT_DB_HOST=127.0.0.1
TENANT_DB_USERNAME=root
TENANT_DB_PASSWORD=your_password

# Test connection
php artisan tinker
>>> DB::connection('tenant')->getPdo();

5. API Authentication Failed

# Check API key in .env
TENANT_API_KEY=sk_tenant_live_your_key_here

# Test API endpoint
curl -H "X-API-Key: your_key" http://your-domain.com/tenancy/tenants

6. Routes Not Working

# Clear route cache
php artisan route:clear
php artisan cache:clear

# Check if routes are registered
php artisan route:list | grep tenancy

Debug Mode

Enable detailed error reporting:

APP_DEBUG=true
LOG_LEVEL=debug
DB_LOGGING=true

Clear All Caches

If you encounter unexpected behavior:

php artisan config:clear
php artisan cache:clear
php artisan route:clear
php artisan view:clear
composer dump-autoload

๐Ÿค Contributing

Development Setup

  1. Clone the repository
  2. Install dependencies: composer install
  3. Run tests: ./vendor/bin/phpunit
  4. Follow PSR-12 coding standards

Reporting Issues

Please use GitHub Issues to report bugs or request features:

  • Provide detailed steps to reproduce
  • Include error messages and stack traces
  • Specify Laravel and PHP versions

๐Ÿ“„ License

This package is open-sourced software licensed under the MIT license.

๐Ÿ™ Credits

๐Ÿ“ˆ Changelog

v0.3.0 - 2025-08-01

Current Release

  • โœ… Fixed API key authentication with proper middleware
  • โœ… Enhanced security with tenancy.api middleware
  • โœ… Proper API rate limiting and throttling
  • โœ… Localhost development mode support
  • โœ… Production-ready API key enforcement
  • โœ… Comprehensive error responses for unauthorized access
  • โœ… Auto-registered API authentication middleware

v0.2.0 - 2025-08-01

Previous Release

  • โœ… Complete multi-tenant Laravel package
  • โœ… Admin dashboard with Metronic UI
  • โœ… Full RESTful API with 30+ endpoints
  • โœ… Comprehensive Artisan commands
  • โœ… Auto-discovery and zero-config setup
  • โœ… Enhanced tenant and domain models
  • โœ… Unified middleware for tenancy
  • โœ… Real-time monitoring and statistics
  • โœ… Production-ready error handling
  • โœ… Backup and restore functionality
  • โœ… Analytics and reporting

Need Help?

Happy multi-tenanting! ๐ŸŽ‰