DEV Community

Cover image for Multi tenancy connect with tenant DB without Initialization Or Dynamically
ARK DEV SOLUTIONS
ARK DEV SOLUTIONS

Posted on

Multi tenancy connect with tenant DB without Initialization Or Dynamically

Multi-Tenancy Without Initialization

In a typical multi-tenancy setup, packages like Stancl/Tenancy are used to initialize tenant context by switching configurations automatically, including the database connection. This involves loading a tenant's specific configuration (like database credentials) after "initializing" the tenancy environment. However, in this case, we're avoiding explicit tenancy initialization and manually connecting to the tenant's database dynamically.

Follow the Steps

Retrieving Tenant Data

Image description

The code starts by retrieving the Tenant record from the central database using the sport_id. This allows us to extract tenant-specific details, such as the database name.

Error Handling for Tenant Existence

Image description

The system ensures that if the Tenant cannot be found using the provided sport_id, it returns an error message to prevent any further processing, ensuring graceful failure handling.

Dynamically Setting Tenant Database Connection

Image description

Here's where the core dynamic connection logic happens:
Manual Configuration: Laravel's config() helper is used to set a new database connection (tenant). This configuration is created on the fly based on the tenant’s database name ($tenantDBName) and uses environment variables for common settings like host, username, and password.
This essentially creates a new connection for this request without altering the default connection defined in Laravel's database.php config file.

Using Tenant Connection

Image description

on('tenant'): The method .on('tenant') explicitly tells Laravel's Eloquent ORM to use the dynamically created tenant database connection (tenant). This ensures that the queries for fetching the article and its relationships are run against the tenant’s specific database, not the central one.
Eager Loading: The code uses Eloquent's with() method to eager load related models like subjects, image, and author. This allows for more efficient database queries by reducing the number of individual queries that would otherwise be required to retrieve these relationships.

Error Handling for Article (or your Model) Retrieval

Image description

In the event that the article cannot be found in the tenant’s database, the system gracefully handles the error by redirecting back with an appropriate message.

Few more things to consider and understand ...

Advantages of This Approach

No Global Tenancy Initialization:

In certain scenarios, initializing a global tenancy environment across requests can be resource-heavy or unnecessary, especially if all you need is to perform isolated operations on a tenant’s database. This approach allows you to connect directly to the tenant’s database when needed, without initializing tenancy for the entire application.

Scalability and Flexibility:

By setting database connections dynamically on a per-request basis, the application is more flexible in handling a large number of tenants. Each tenant’s connection is isolated and only created when necessary.

Use Case:
This approach is particularly useful in applications where you have different databases for tenants but share most other resources, like codebase, environment settings, or other global configurations. This technique avoids the overhead of multi-tenant packages but still provides isolation for database-related operations.

Limitations

Database Connections Per Request:

Every time this method is called, it dynamically sets a new connection. While efficient for small-scale applications, this could become resource-intensive for a high number of concurrent users or tenants. Managing the lifecycle of these connections should be done carefully.

Conclusion

The above code effectively handles dynamic multi-tenancy by connecting to a tenant’s database without using a tenancy package or initializing a global tenancy context. This approach offers flexibility, especially for applications where only certain operations need to be tenant-aware, and avoids the complexity and overhead of managing tenancy at a global level.

It's an elegant solution for applications with isolated tenant databases but shared application logic and infrastructure, aligning well with Laravel's philosophy of simplicity and flexibility.

Top comments (0)