logo
podcast Podcast
get help Get Unstuck

Sharing a model between landlord and tenant

A little tricky in a multi-database environment

Joel Clermont
Joel Clermont
2024-07-24

On a recent project, the client was using a multi-tenancy approach where each tenant had their own database, and there was also a single central "landlord" database.

The Spatie multi-tenancy package supports this approach, but there's an assumption baked in that a model is either for the landlord or for a tenant. The recommendation is to add the corresponding trait UsesLandlordConnection or UsesTenantConnection to the model to indicate where it should be used.

In this project, that assumption did not hold true. There were about ten models that would exist both on the landlord and tenant databases.

How did we handle it? We wrote our own trait to dynamically set up the correct database connection:

trait UsesTenantAndLandlordConnections
{
    use UsesMultitenancyConfig;

    public function getConnectionName()
    {
        if (Tenant::checkCurrent()) {
            return $this->tenantDatabaseConnectionName();
        }

        return $this->landlordDatabaseConnectionName();
    }
}

By overriding this one function, and checking the state of the current request, we were able to dynamically set the correct database connection for landlord versus tenant. And it relied on the built-in mechanisms from the package so everything remained consistent.

This approach works great when the models are identical between landlord and tenant. If there was any deviation, you'd need to create two separate models.

Here to help,

Joel

P.S. So often we join a project after a big architectural decision like this has already been made. If you'd like an experienced Laravel developer to review a big decision on your project, we can help.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.