• Laravel
  • 2 MINUTES READ

Build Powerful Multi-Tenant Application using Laravel 4 and 5

  • POSTED ON
  • November 16, 2015
  • POSTED BY
  • Aayan Arif
  • POSTED ON November 16, 2015
  • POSTED BY Aayan Arif

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....

Nowadays, Multi-Tenant Application using Laravel 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. We built the Multi-Tenant Application using Laravel. 

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:

namespace AppHttpMiddleware;
use AppSites;
use Closure;

class config
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $site_url = $_SERVER['SERVER_NAME'];
        
        $site = Sites::where('site_url',$site_url)->first();

        $config = array();        
        
        if(!is_null($site)){

            $config['id'] = $site["id"];
            $config['site_url'] = $site["site_url"];
            $config['theme'] = $site["theme"];
            $config['host'] = $site["host"];
            $config['db_name'] = $site["database"];
            $config['user'] = $site["user"];
            $config['password'] = $site["password"];
            $config['prefix'] = $site["prefix"];
            
        }else{
 //default values
            $config['id'] = "0";
            $config['site_url'] = "demo.local";
            $config['theme'] = "theme";
            $config['host'] = "localhost";
            $config['db_name'] = "dbname";
            $config['user'] = "username";
            $config['password'] = "password";
            $config['prefix'] = "tbl";           
        }    
        //dd($config);
        // Session::put('config', $config);

        Config::set('database.connections.mysql.host', $config['host'] );
        Config::set('database.connections.mysql.database', $config['db_name'] );
        Config::set('database.connections.mysql.username', $config['user']);
        Config::set('database.connections.mysql.password', $config['password']);
        Config::set('database.connections.mysql.prefix', $config['prefix']);

        Config::set('database.connections.mysql.theme', $config['theme']);
        
        DB::reconnect();

        return $next($request);
    }
}

Step 4: Update Routes

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

Route::group(['middleware' => 'config'],function (){
       Route::get('/', ['uses' => 'HomeController@page']);
});

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.

Building a Multi-Tenant Application using Laravel

So if this article somewhere convinced you that SaaS development outsourcing is the right fit for your next product and is worth a shot, our experts at vteams would be more than happy to assist, giving you the best of both worlds.

ABOUT THE AUTHOR

Aayan Arif

Content Strategist at vteams - Aayan has over 8 years of experience of working with multiple industries.

0 Comments

Leave a Reply

More Related Article
We provide tips and advice on delivering excellent customer service, engaging your customers, and building a customer-centric business.