Created
July 18, 2014 09:50
-
-
Save fer-ri/39843951b1992f7e7ed2 to your computer and use it in GitHub Desktop.
Set Database Config On The Fly for Laravel Multi Tenant
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// app/filters.php | |
App::before(function($request) | |
{ | |
// get current host and replace . with _ | |
$host = str_replace('.', '_', $request->getHost()); | |
// get current config based on $host | |
$config = Config::get('sites/' . $host); | |
// create global object from $config | |
App::singleton('siteConfig', function() use ($host, $config){ | |
return json_decode(json_encode($config), FALSE); | |
}); | |
if ( ! $config) { | |
return App::abort('404'); | |
} | |
// set database config on the fly | |
Config::set('database.connections.currentHost', [ | |
'driver' => $config['db']['driver'], | |
'host' => $config['db']['host'], | |
'database' => $config['db']['database'], | |
'username' => $config['db']['username'], | |
'password' => $config['db']['password'], | |
'charset' => $config['db']['charset'], | |
'collation' => $config['db']['collation'], | |
'prefix' => $config['db']['prefix'], | |
]); | |
// set default connection for this $host | |
DB::setDefaultConnection('currentHost'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment