Multi-tenant SaaS applications require careful architecture. Laravel provides flexible patterns for tenant isolation through middleware, database switching, and subdomain routing. At ZIRA Software, we've built multi-tenant platforms serving thousands of organizations with complete data isolation.
Multi-Tenancy Approaches
1. Database per tenant:
- Complete isolation
- Easy backup/restore
- Higher costs
- Complex migrations
2. Shared database with tenant_id:
- Cost effective
- Simple migrations
- Requires careful queries
- Schema shared
3. Hybrid approach:
- Shared users table
- Tenant-specific databases
- Balance of both
Implementation
Tenant model:
class Tenant extends Model
{
protected $fillable = ['name', 'subdomain', 'database'];
}
Middleware:
public function handle($request, Closure $next)
{
$subdomain = explode('.', $request->getHost())[0];
$tenant = Tenant::where('subdomain', $subdomain)->firstOrFail();
config(['database.connections.tenant.database' => $tenant->database]);
DB::purge('tenant');
DB::setDefaultConnection('tenant');
app()->instance('tenant', $tenant);
return $next($request);
}
Global scope for shared database:
trait BelongsToTenant
{
protected static function bootBelongsToTenant()
{
static::addGlobalScope(new TenantScope);
static::creating(function ($model) {
$model->tenant_id = app('tenant')->id;
});
}
}
class TenantScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
$builder->where('tenant_id', app('tenant')->id);
}
}
Conclusion
Multi-tenancy enables scalable SaaS applications. Choose the right approach for your needs. At ZIRA Software, we've successfully deployed both patterns.
Building a multi-tenant SaaS application? Contact ZIRA Software for architecture consultation.