artflow-studio / tenancy
A comprehensive multi-tenant Laravel package with admin dashboard and domain management. Optimized for performance with proper stancl/tenancy integration.
Requires
- php: ^8.1
- illuminate/support: *
- predis/predis: *
- stancl/tenancy: *
Requires (Dev)
- phpunit/phpunit: ^10.0
README
Version: 0.6.0 - Central Domain Support & Smart Domain Resolution
๐ High-Performance Laravel Multi-Tenancy - Built on top of stancl/tenancy
with comprehensive database isolation, performance optimizations, and 100% tenant isolation with enterprise features.
โ Current Status - PRODUCTION READY
๐ NEW IN v0.6.0 - CENTRAL DOMAIN SUPPORT:
- โ Smart Domain Resolution - Automatic routing between central and tenant domains
- โ Central Domain Middleware - No more "Tenant not found" errors on 127.0.0.1/localhost
- โ Mixed Environment Support - Admin dashboards on central, tenant content on tenant domains
- โ Zero Configuration Required - Works out of the box with sensible defaults
- โ 100% Backward Compatible - All existing routes continue to work unchanged
- โ Performance Optimized - Central domains bypass tenant resolution entirely
๐ ENTERPRISE FEATURES:
- โ 100% Database Isolation - Complete tenant separation with UUID-based databases
- โ High Performance - 46+ req/s with database switching, optimized for 100+ concurrent tenants
- โ Event-Driven Architecture - Complete tenancy lifecycle management
- โ Performance Monitoring - Built-in health checks and performance analysis
- โ stancl/tenancy Integration - Full compatibility with enhanced features
- โ Laravel 11.x Support - Latest Laravel integration with optimizations
- โ Connection Pooling - Persistent connections and optimized database management
๐ฆ COMPLETE PACKAGE CONSOLIDATION:
- โ All configurations moved to package directory
- โ Comprehensive documentation included
- โ Installation guides and stubs provided
- โ Performance analysis and monitoring tools
๐ Quick Environment Setup
Add these to your .env
file:
# Tenant Database Configuration TENANT_DB_PREFIX=tenant_ TENANT_DB_CONNECTION=mysql TENANT_DB_HOST=127.0.0.1 TENANT_DB_PORT=3306 TENANT_DB_USERNAME=root TENANT_DB_PASSWORD= TENANT_DB_CHARSET=utf8mb4 TENANT_DB_COLLATION=utf8mb4_unicode_ci TENANT_DB_PERSISTENT=true # Tenant API Security TENANT_API_KEY=sk_tenant_live_kjchiqgtsela047mb31vrwf25xop9ny8 TENANCY_API_KEY=sk_tenant_live_kjchiqgtsela047mb31vrwf25xop9ny8 TENANCY_BEARER_TOKEN=bearer_kjchiqgtsela047mb31vrwf25xop9ny8 # Performance & Configuration TENANT_AUTO_MIGRATE=true TENANT_AUTO_SEED=false CACHE_DRIVER=array APP_DOMAIN=localhost
๐ Installation
One-Command Installation (Recommended)
composer require artflow-studio/tenancy php artisan artflow:tenancy --install
Complete automated setup in seconds!
What happens during installation:
- โ Publishes optimized tenancy configurations
- โ Enables cached lookup for 10x performance boost
- โ Runs database migrations automatically
- โ Sets up API authentication with secure keys
- โ Configures Redis caching optimization
- โ Consolidates all routes into af-tenancy.php
Quick Test
# Health check php artisan tenancy:health # Performance test (63+ req/s expected) php artisan tenancy:test-performance # Create test tenants php artisan tenancy:create-test-tenants --count=3
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
๏ฟฝ 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
anddomains
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
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
๐ License
This package is open-sourced software licensed under the MIT license.
๐ Credits
- Built on top of stancl/tenancy - The best Laravel tenancy package
- Developed by Artflow Studio
๐ Support
- Documentation: API.md | COMMANDS.md | ROADMAP.md
- Issues: GitHub Issues
- Email: support@artflow-studio.com
๐ 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
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Write tests for your changes
- Ensure all tests pass
- Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Code Standards
- Follow PSR-12 coding standards
- Write comprehensive tests
- Document new features
- Update CHANGELOG.md
๐ Support & Community
Documentation & Resources
- ๐ Full Documentation: https://tenancy.artflow-studio.com
- ๐ฅ Video Tutorials: YouTube Channel
- ๐ API Reference: API Documentation
Community Support
- ๐ฌ Discord Community: Join our Discord
- ๐ฃ๏ธ GitHub Discussions: GitHub Discussions
- ๐ Bug Reports: GitHub Issues
- ๐ก Feature Requests: Feature Request Portal
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
- ๐ Blog: Tenancy Best Practices
- ๐ Courses: Laravel Multi-Tenancy Mastery Course
- ๐ Case Studies: Real-world implementation examples
- ๐ ๏ธ Tools: Free migration and analysis tools
๐ License
This package is open-sourced software licensed under the MIT license.
๐ Sponsors & Credits
Built With
- stancl/tenancy - The foundational tenancy package
- Laravel Framework - The web artisan framework
- PHP - The backbone of our application
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:
- GitHub Sponsors: Sponsor on GitHub
- Open Collective: Support via Open Collective
๐ Star History
Made with โค๏ธ by Artflow Studio
Empowering developers to build scalable multi-tenant applications with ease
| `/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
- Navigate to
/admin/dashboard
- Click "Create New Tenant"
- 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
Available Middleware
The package provides three middleware options for different routing needs:
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) });
3. Traditional Tenant (tenant
)
Standard tenant-only routes:
// In your routes/tenant.php - tenant domains only Route::middleware(['tenant'])->group(function () { Route::get('/tenant-dashboard', [TenantController::class, 'dashboard']); Route::resource('customers', CustomerController::class); // Only accessible from tenant domains });
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); });
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 domainstatus
(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 namedomain
(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 notesrun_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 operationalsuspended
: Temporary access restrictionblocked
: Permanent access restrictioninactive
: 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
- Clone the repository
- Install dependencies:
composer install
- Run tests:
./vendor/bin/phpunit
- 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
- Built on top of stancl/tenancy
- UI components from Metronic
- Developed by Artflow Studio
๐ 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?
- ๐ Read the docs above
- ๐ Report issues
- ๐ง Email: support@artflow-studio.com
Happy multi-tenanting! ๐