Simplifying Tenant Management in Reimpact Platform

The Challenge

In multi-tenant applications, managing data isolation is crucial. The Reimpact platform, designed for managing various industrial processes, initially relied on company_id filtering within each database table to achieve this isolation. This approach, while functional, introduced redundancy and complexity across our Eloquent models.

The Solution: PostgreSQL Schema Isolation

We transitioned to PostgreSQL schema isolation, leveraging the SET search_path command. This allows each tenant to operate within its dedicated schema, providing a cleaner and more robust isolation mechanism. This change involved refactoring our Eloquent models to remove the reliance on company_id.

Removing company_id

The company_id column was removed from the $fillable array, PHPDoc, and company() relationships in our models. The BelongsToTenant trait was also updated to reflect this change. This refactoring spanned across five modules: Packaging, Textiles, Tires, AEEAndCells, and Batteries.

// Example: User model before
class User extends Authenticatable
{
    use HasFactory, Notifiable, BelongsToTenant;

    protected $fillable = [
        'name',
        'email',
        'password',
        'company_id', // Removed
    ];

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class); // Removed
    }
}

// Example: User model after
class User extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];
}

The key change here is the removal of company_id from the $fillable array and the removal of the company() relationship. This ensures that the model no longer directly interacts with the company_id at the Eloquent level.

Database Migrations

To complete the transition, we created a migration to drop the company_id column from duplicated tables in the public schema (warehouses, brands, products, etc.).

Deployment Order

We also adjusted the deployment order to ensure that tenants:migrate is executed before migrate. This guarantees that tenant schemas are created before any migrations that depend on them are run.

Preserving Declarant Column

Finally, we updated the PopulateTenantSchemas process to preserve the declarant column during schema population.

Benefits

  • Simplified Models: Removal of company_id made our Eloquent models cleaner and easier to maintain.
  • Improved Isolation: PostgreSQL schema isolation provides a more robust and reliable mechanism for tenant data separation.
  • Reduced Redundancy: Eliminating company_id filtering reduced code duplication and complexity.

By adopting PostgreSQL schema isolation and removing the company_id from our models, we've significantly improved the maintainability and scalability of the Reimpact platform.

Simplifying Tenant Management in Reimpact Platform
GERARDO RUIZ

GERARDO RUIZ

Author

Share: