iMasters.com - Knowledge for Developers.
Follow Us
Home Backend Simple Multi-Tenant Setup in Laravel
Backend

Simple Multi-Tenant Setup in Laravel

What is Multi-Tenant?

It is an architecture in which a single application instance serves multiple clients. Each customer is called a Tenant. Tenants may have the ability to customize some parts of the application, such as the color of the UI or business rules, but they cannot change the code.

Laravel makes it very easy to do this. All you need is a connection configuration, a Middleware, and a Trait and configure your Models. Let’s do this in practice.

Simple Multi-Tenant Setup in Laravel

Connection Settings

In your config/database.php file, we will define two connections. Note that I delete the MySQL connection, so it is necessary to configure the .env file for the new connection driver.

The Middleware

Always ensure the connection exists. Ensure that all routes connect to a tenant’s database using this middleware. In my particular situation, the user would select a customer (tenant) from a list and manipulate that customer’s data, hence the use of the session. But I could easily have two middlewares (WebTenant, ApiTenant) and rely on tokens to choose a tenant connection as well.

TenantConnector (A Trait)

Not much to talk about here, just your tenant connection defined.

The Models

A main model will have the main connection and nothing else.

The Company model (customer/tenant) was different. I used the Trait TenantConnector and wrote the connect() method. This allows me to do things like Company:: find($id)->connect();

A Tenant Model will only use the tenant connection.

The last thing would be the SelectTenantController, to let you define the session the middleware expects.

Conclusion

Laravel makes it easy to have two connection setups. Routes will connect to a specific database and can easily have middleware to ensure the connection exists. You can easily choose the connection for each Model (or have a MainModel/TenantModel and extend them). Everything is set up, and you have a Laravel application capable of connecting to multiple databases.

Written by
Douglas Carlos Men

PHP developer for 4 years. Knowledgeable of this incredible language, with a special affection for the Laravel Framework.

Leave a comment

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Related Articles

Backend

How to Create a Skill for Amazon’s Virtual Assistant Alexa

If you didn’t know, it is not necessary for an Amazon Echo...

Backend

The APIs role in a 5G world

5G is about to revolutionize how we connect and use technology daily....

Backend

EF Core using AsNoTracking with Identity Resolution

Today we will see the consequences of using AsNoTracking with the Identity...

Backend

Understand key features added in ASP.NET Core 7.0

Version 7.0 of the .NET platform brought many new features in this...