This is the best way to do this. In the end, all this is an opinion. However, I would like to create a connection in the configuration file for each of the subdomains. Then, in your connectSubdomainDatabase () function, I would get the current subdomain instead of passing the database name. You can already specify the connection in laravel, the only place you should use the database names is in the configuration file.
So something like this:
// To connect with a subdomain - the entry will be in config/database.php. public static function connectSubdomainDatabase() { // Break apart host $urlParts = explode('.', $_SERVER['HTTP_HOST']); // Change default connection Config::set('database.default', $urlParts[0]); }
If the connections are config / database.php:
'connections' => [ 'subdomain1' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ], 'subdomain2' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ], ],