Search code examples
phplaravellaravel-5subdomainlaravel-5.1

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.


Solution

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