问题
This might not be an appropriate question for stackoverflow....as it might be too specific.
But I was wondering if anybody knows how I would have one installation of Laravel, serving a site. But depending on the url, I can access different databases.
Ie...
www.mainsite.com/company1/login - database1
www.mainsite.com/company1/users - database1
..
www.mainsite.com/company2/login - database2
www.mainsite.com/company2/users - database2
So in the cases above, the site being served is the exact same site. But of course, each part has a login, and accesses a different database.
I know I can do this by having multiple installations of laravel, and thats actually how Im doing it right now....
But I wanna be able to just update ONE version....instead of having to copy my changes to all the different folders.
Then just serve that one site to all the multiple different companies. With them having access to only their database
Is this possible??
回答1:
You could define multiple databases in your config:
'default' => 'database1',
'connections' => array(
'database1' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database1',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
),
'database2' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
),
),
Then query using fluent:
$user = DB::connection('database2')->table('users')->where('id', '=', 1)->first();
Maybe you could use environments, something like this:
$environments = array(
'company1' => array('http://server.com/company1*'),
'company2' => array('http://server.com/company2*'),
);
Then create your subfolders in the config and copy of the db config to edit as needed.
回答2:
One technique I used for this was to generate database names for new customers who sign up and store that in my master database. The database would be created and migrated at this time as well. When the user logins in everytime after that, the software looks up his database name and sets the config for them on the fly using:
Config::set(['database.connections.customerid'])
.
You can still have all the goodies Laravel and Eloquent offer and not be reliant on raw queries. This also frees you from managing a large config file. I also created resource directories matching their schema name so they could have a custom front facing site with view files and styles while running the exact same stack as everyone else.
来源:https://stackoverflow.com/questions/17624155/different-databases-same-site-with-laravel