Skip to content

Instantly share code, notes, and snippets.

@fer-ri
Created July 18, 2014 09:50
Show Gist options
  • Save fer-ri/39843951b1992f7e7ed2 to your computer and use it in GitHub Desktop.
Save fer-ri/39843951b1992f7e7ed2 to your computer and use it in GitHub Desktop.
Set Database Config On The Fly for Laravel Multi Tenant
<?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