Multi-tenant in Laravel4

2019-01-23 00:05发布

问题:

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.