Multi-tenant in Laravel4

岁酱吖の 提交于 2019-11-27 14:15:00

问题


I'm building a multi-tenant app, using the subdomain to separate the users. e.g. .myapp.com

I want to give each tenant their own database too.

How can I detect the subdomain and set the database dynamically?

Also, the code below is from the official documentation and shows us how we can get the subdomain when setting up a route. But how do we pass the subdomain value to a controller function?

Route::group(array('domain' => '{account}.myapp.com'), function()
{

    Route::get('user/{id}', function($account, $id)
    {
        //
    });

});

回答1:


The best way to achieve this would be in a before filter that you apply to the route group.

Route::group(['domain' => '{account}.myapp.com', 'before' => 'database.setup'], function()
{
    // Your routes...
}

This before filters gets a $route parameter and a $request parameter given to it, so we can use $request to get the host.

Route::filter('database.setup', function($route, $request)
{
    $account = $request->getHost();
}

You could then use the account to adjust the default database connection using Config::set in the filter. Perhaps you need to use the default connection first up to fetch the users database details.

$details = DB::details()->where('account', '=', $account)->first();

// Make sure you got some database details.

Config::set('database.connections.account', ['driver' => 'mysql', 'host' => $details->host, 'database' => $details->database, 'username' => $details->username, 'password' => $details->password]);

Config::set('database.connections.default', 'account');

During runtime you create a new database connection and then set the default connection to that newly created connection. Of course, you could leave the default as is and simply set the connection on all your models to account.

This should give you some ideas. Please note that none of this code was tested.

Also, each method on your controllers will receive the domain as the first parameter. So be sure to adjust for that if you're expecting other parameters.



来源:https://stackoverflow.com/questions/16879803/multi-tenant-in-laravel4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!