Download the PHP package roberts/laravel-singledb-tenancy without Composer
On this page you can find all versions of the php package roberts/laravel-singledb-tenancy. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download roberts/laravel-singledb-tenancy
More information about roberts/laravel-singledb-tenancy
Files in roberts/laravel-singledb-tenancy
Package laravel-singledb-tenancy
Short Description Laravel package for single database multi-tenancy
License MIT
Homepage https://github.com/roberts/laravel-singledb-tenancy
Informations about the package laravel-singledb-tenancy
Laravel Single Database Tenancy
A Laravel package for single-database multi-tenancy. It offers automatic data isolation, tenant resolution by domain, and flexible routing, making it a complete solution for SaaS applications.
Features
- Automatic Tenant Resolution: Resolve tenants by domain or subdomain.
- Data Isolation: Automatically scope Eloquent models to the current tenant.
- Tenant Context: Global helper functions (
current_tenant()) to access the active tenant. - Smart Fallback: Automatically fall back to a primary tenant if no tenant is resolved.
- Caching: Fast tenant resolution via configurable caching.
- Tenant-Specific Routing: Support for loading custom route files for each tenant.
- Artisan Commands: Built-in commands for migrations and diagnostics.
- Forced Tenant Mode: Simplify development and testing by forcing a specific tenant.
Requirements
- PHP 8.5+
- Laravel 13.0+
Installation
Install the package via Composer:
Publish and run the migrations:
Publish the configuration file:
Configuration
The package provides extensive configuration options in config/singledb-tenancy.php:
Caching Configuration
Error Handling
Basic Usage
1. Creating Tenants
2. Making Models Tenant-Aware
Add the HasTenant trait to your models. It automatically scopes queries to the current tenant, sets the tenant_id on creation, and adds a tenant() relationship.
This automatically applies tenant scoping to queries, sets tenant_id on creation, and provides a tenant() relationship.
3. Setting Up Middleware
Apply the tenant resolution middleware to your routes:
Advanced Features
Tenant-Aware Jobs
To make your queued jobs tenant-aware, simply use the TenantAware trait. It automatically captures the tenant context when the job is dispatched and restores it when the job is processed.
Tenant-Aware Commands
Create tenant-aware artisan commands by extending the TenantAwareCommand class. This automatically provides --tenant=<id> and --all-tenants options.
Implement your logic in the handleTenant() method, where the tenant context is guaranteed to be set.
Tenant Lifecycle Events
The package dispatches events to allow you to hook into the tenant lifecycle:
TenantCreated: After a new tenant is created.TenantResolved: After the tenant context is set for a request.TenantSuspended: After a tenant is suspended.TenantReactivated: After a tenant is reactivated.TenantDeleted: After a tenant is soft deleted.
You can listen for these events in your EventServiceProvider:
Tenant Context Management
The package provides global helper functions for tenant context:
Manual Tenant Context
You can manually set the tenant context:
Model Scoping
Tenant-aware models are automatically scoped:
Custom Route Files
You can create tenant-specific route files in the routes/tenants/ directory. The file name should match the tenant's domain.
Important: When a custom route file is found for a tenant, it overrides the default routes/web.php file. If you want to augment the default routes, you must manually include them at the botttom of your tenant's route file:
Development and Testing
Force a specific tenant during development:
Disable tenant resolution for tests that need to see all data:
Tenant Resolution
The package uses domain-based resolution to match the full request domain against the domain column in your tenants table. This works for both root domains and subdomains.
How It Works
Database Structure
Your tenants table should contain complete domain entries:
If no tenant is resolved, the Smart Fallback Logic can automatically fallback to a designated primary tenant.
Smart Fallback Logic
The Smart Fallback Logic provides automatic fallback to a primary tenant when normal resolution fails. This ensures your application always has a valid tenant context, which is particularly useful for shared content or landing pages.
How It Works
- Normal Resolution: First attempts standard domain/subdomain resolution
- Fallback Check: If no tenant is found and fallback is enabled, checks for primary tenant
- Primary Tenant: Falls back to tenant with ID 1 (configurable)
- Smart Skipping: Automatically skips fallback when no tenants exist in the database
- Suspension Respect: Won't fallback to suspended primary tenant
Caching Behavior
- Primary tenant existence is cached permanently once confirmed
- Cache is invalidated when tenants are deleted
- Tenant existence cache prevents unnecessary database queries
Use Cases
- Landing Pages: Serve shared content when no tenant is specified
- Marketing Sites: Display default content for non-tenant visitors
- Development: Consistent behavior during application setup
- Error Recovery: Graceful handling of misconfigured domains
Management Commands
The package includes helpful Artisan commands for managing your tenancy setup:
Add Tenant Column Command
Quickly add tenant_id columns to existing tables with proper foreign key constraints:
Tenancy Info Command
Display comprehensive information about your tenancy configuration and current state:
This command shows:
- Resolution strategy status
- Caching configuration
- Current tenant context
- Database tenant statistics
- Smart Fallback Logic settings
Caching
Tenant resolution results are cached automatically to improve performance. Cache is invalidated when tenants are modified.
Error Handling
Unresolved Tenant
When no tenant can be resolved from the request:
fallback- Use Smart Fallback Logic to primary tenantcontinue- Continue without tenant contextexception- Throw RuntimeExceptionredirect- Redirect to specified route
Suspended (soft deleted) tenants are automatically blocked and will not be resolved.
Security
Super Admin
You can designate a single "super admin" user who has privileges over the entire tenancy system (e.g., for accessing a future admin panel). This is configured by setting an environment variable:
The package provides a SuperAdmin service to check if a user is the designated super admin:
Primary Tenant Authorization
The package includes a middleware to restrict access to routes that should only be available on the primary tenant's domain (i.e., the tenant with ID 1). This is useful for creating a centralized admin panel.
To use it, simply add the auth.primary middleware to your routes:
If a user attempts to access this route from any domain other than the primary tenant's, they will receive a 404 Not Found error.
Testing
Run the comprehensive test suite:
Test your tenant-aware code:
API Reference
Models
Tenant
Services
TenantContext
TenantCache
Automatic caching of tenant resolution - no direct usage required.
Middleware
TenantResolutionMiddleware
Configuration Reference
Full Configuration File
Environment Variables
Migration
This package includes a tenant migration that creates the tenants table:
Add tenant_id to your existing tables:
Or use the built-in command:
Best Practices
- Always use the HasTenant trait on models that should be tenant-aware
- Cache tenant resolution in production for better performance
- Test tenant isolation thoroughly to prevent data leaks
- Use tenant context helpers instead of manual database queries
- Configure reserved subdomains to avoid conflicts with system routes
- Implement proper error handling for unresolved tenants
Troubleshooting
Tenant not resolving: Verify middleware is applied, check configuration, ensure tenant exists Data leaking between tenants: Confirm HasTenant trait usage and tenant context Cache issues: Verify cache configuration and clear stale data Custom routes not loading: Check file naming, path existence, and syntax
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
- Drew Roberts
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-singledb-tenancy with dependencies
filament/filament Version ^5.6.1
roberts/support Version ^2.0
spatie/laravel-package-tools Version ^1.92
illuminate/contracts Version ^13.0