I've solved this myself:
First of all, we create a route group to the subdomain, excluding 'www' with a pattern:
Route::pattern('id', '[0-9]+');
Route::group(array('domain' => '{subdomain}.mysite.com', 'before' => 'switchDB'), function() {
// Publicly accessible routes under the subdomain
Route::group(array('before' => 'guest'), function() {
// login routes (get and post)
});
// Routes under the subdomain that require authentication
Route::group(array('before' => 'auth'), function() {
});
});
// Publicly accessible routes in the main domain
Route::get('/', array('uses' => 'PublicController@showHome'));
Then the filter, where we get the subdomain and check in our default database (global database) what account has that domain. We also check if that database exists.
Route::filter('switchDB', function($route, $request) {
$parts = explode('.', $request->getHost());
$subdomain = $parts[0];
$account = Account::where('subdomain', '=', $subdomain)->first();
if($account == null) {
App::abort(404);
}
$res = DB::select("SHOW DATABASES LIKE '" . $account->db_name . "'");
if(count($res) == 0) {
App::abort(404);
}
Config::set('database.connections.mysql.database', $account->db_name);
DB::reconnect();
Session::put('subdomain', $subdomain);
});
The DB::reconnect() seems to be a key player in all of this.