How can I handle subdomains with one laravel installation

前端 未结 7 2026
爱一瞬间的悲伤
爱一瞬间的悲伤 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

    I would do that way:

    • Create one database per domain

    • Set up the available DB connections in laravel config/database.php :

    'connections' => [
    
         'mysql_domain_1' => [
            'driver'    => 'mysql',
            /* other config values... */
        ],
    
        'mysql_domain_2' => [
            'driver'    => 'mysql',
            /* other config values... */
        ]
    ];
    
    • In the early fase of the request cycle (for example in a Middleware), get the sub-domain from the request, and set the current DB connection accordingly

      For example create a middleware and in the handle method:

    public function handle($request, Closure $next)
    {
        //check the request URL and get subdomain
    
        //get the db connection associated to the subdomain 
    
        //set the connection for this request
        Config::set('database.default', $dbConnection);
    } 
    

    Config::set('database.default', $dbConnection ); will set the db connection used by the whole application for the current request cycle

提交回复
热议问题