1. Introduction to Multi-Tenant Applications
Multi-tenancy allows a single Laravel application to serve multiple customers (tenants) with data isolation. This is commonly used in SaaS applications.
2. Approaches to Multi-Tenancy in Laravel
- Single Database, Tenant Identification: Uses a shared database with tenant-specific identifiers.
- Multiple Databases: Each tenant gets a separate database.
- Schema-Based Isolation: Uses PostgreSQL schemas for each tenant.
3. Setting Up Laravel Multi-Tenancy
Install the stancl/tenancy
package:
composer require stancl/tenancy
4. Configuring Tenant Model
Define the Tenant model in app/Models/Tenant.php
:
use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;
class Tenant extends BaseTenant {
protected $fillable = ['id', 'data'];
}
5. Creating Tenants
Create a new tenant using:
use App\Models\Tenant;
$tenant = Tenant::create(['id' => 'example.com']);
$tenant->domains()->create(['domain' => 'example.com']);
6. Middleware for Tenant Identification
Update middleware to detect the current tenant:
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains;
protected $middlewareGroups = [
'tenant' => [
InitializeTenancyByDomain::class,
PreventAccessFromTenantDomains::class,
],
];
7. Running Tenant Migrations
To create tables for each tenant:
php artisan tenants:migrate
8. Conclusion
Laravel provides powerful multi-tenancy capabilities for SaaS applications. By structuring data correctly, you can ensure security, scalability, and performance.
0 Comments