Ad

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.

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad