Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

laravel - Multi-tenant in Laravel4

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)
    {
        //
    });

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...