Programmer Notes

Multi-Tenant Application using Laravel 4 and 5

Nowadays, Multi-Tenant or SaaS based applications are all over the web. Concept behind multi-tenancy is to use single code base to serve multiple clients with same functionality. Recently, we interacted with a client who was managing several schools. He wanted to keep every school separate from one another on different sub-domains with separate databases.

To achieve the required functionality, we performed the following steps:

Step 1: Database Types

We needed a main database and several other databases for each and every school. The main database was used to manage the following instances of schools:

  • ID
  • Name
  • Domain Name
  • Theme
  • database_name
  • database_user
  • database password encoded
  • Status
    .

If a domain name would exist in main database and had an active status then the application would proceed normally. Database would likewise be loaded as per the provided information.

Step 2: Sub-Domains

Every sub-domain would point to the same code and same folder on Server.

Step 3: Select Database

The Database would be chosen by means of a filter (Laravel 4) or middleware (Laravel 5) contingent upon the version of Laravel framework.  Every request would land on filter or middleware before reaching to any other page. To achieve this functionality, routes setup was needed.

A middleware was created where we implemented a code to check the sub-domain status if it is accessing the code (which exists in main database) or not. If the code existed in database then it would be fine or else sub-domain would be redirected to error page. The middleware example is given below:

Step 4: Update Routes

To use middle-ware, we had to update route as follows:

Note: This route stated that if the application would try to access anything from the configured route then it would hit middleware and check if proper database was selected or not.

Conclusion:

To implement multi-tenancy functionality, the only change required is to use Middleware code in a Filter.