How can I handle subdomains with one laravel installation

前端 未结 7 1990
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 09:19

I am creating a laravel project for which I need one laravel installation and use its instance in sub-domain with separate database. And th

7条回答
  •  一生所求
    2020-12-29 10:02

    Here's how I would approach this:

    In your config/database.php:

     'mysql',
            'host'      => 'localhost',
            'database'  => 'master',
            'username'  => 'master_user',
            'password'  => 'master_password',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        );
        array_push($connectionParams, array('mysql' => $connParams);
    
        // TODO: connect to your master database using PDO/mysqli or anything else you know.
        // The point is: you can't use Laravel ORM just yet because you are currently setting up its configuration!
        // Get the list of subdomain connection parameters and array_push it to $connectionParams just like above.
        // Example:
        // array_push($connectionParams, array('subdomain' => $subdomainConnParams)
    
        return $connectionParams;
    }
    
    return array (
        'default' => 'mysql'
    
        ,'connections' => getDatabaseConnectionParameters()
    )
    ?>
    

    With this, subdomain specific models only need to specify $connection correctly. Example:

    
    

    This way, your subdomain database configurations could be saved in your master database, while making your models simple and still Laravel-ful. Also, there is no nasty hacks that would make upgrading Laravel version hard.

提交回复
热议问题