Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle subdomains with one laravel installation

I am creating a laravel project for which I need one laravel installation and use its instance in sub-domain with separate database. And those separate database's info will not be in config/database.php. It will get from master database and then reconnected to the other database.

I didn't find any proper way to do this.

Do you have any idea on this ?

Thanks for your time.

like image 956
Niklesh Raut Avatar asked Dec 16 '15 10:12

Niklesh Raut


2 Answers

Laravel supports multiple Database connections. Firstly, define the connections in config/database.php:

<?php
return array(

    'default' => 'default_connection',

    'connections' => array(

        // domain.com
        'default_connection' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'primary_database',
            'username'  => 'username',
            'password'  => 'password'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        // sub.domain.com
        'subdomain_connection' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'secondary_database',
            'username'  => 'username',
            'password'  => 'password'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

Now to specify which connection your models should use you can set the $connection property in your models:

<?php

class YourModel extends Eloquent {

    protected $connection = 'subdomain_connection';

}

You can set the value of $connection programatically.

like image 188
noodles_ftw Avatar answered Sep 21 '22 14:09

noodles_ftw


Multi-tenancy is a tricky architecture that needs care to model. There are several ways to achieve this architecture. Some decide to use a single database whiles others prefer to use multiple database(that is in your case).

They both have their pros and cons that you need to consider. There are a lot of factors that need to be taken into consideration before you start modeling your application. eg Virtual host configuration for subdomains, Database migration(rollback all databases when the need be, etc.). I will suggest these two packages that can help you going and give you more insight on how to model your application to suite what you want.

https://github.com/orchestral/tenanti

https://github.com/hyn/multi-tenant

like image 25
oseintow Avatar answered Sep 19 '22 14:09

oseintow