I want to develop code based web applications, each website has its own database, not about the views. I saw many tutorials using DB::connection('connection_name')
in the controller or set the protected $connection = 'connection_name';
in the model. I don't like this approach. I have done this with a different approach and I am wondering if my approach is a correct way, efficient and a best practice or it leads to any disadvantages.
This is how I do it in Laravel 5.7.
In the .env
file, I define different database informations.
DB_CONNECTION='mysql'
DB_HOST='my_h'
DB_PORT='my_p'
DB_DATABASE='my_db'
DB_USERNAME='my_un'
DB_PASSWORD='my_pw'
DOMAIN_NAME_V1 = 'my_domain_v1.com'
TEMPLATE_NAME_V1 = 'my_domain_v1'
DB_CONNECTION_V2='mysql2'
DB_HOST_V2='my_host_v2'
DB_PORT_V2='my_port_v2'
DB_DATABASE_V2='my_db_v2'
DB_USERNAME_V2='my_username_v2'
DB_PASSWORD_V2='my_pw_v2'
DOMAIN_NAME_V2 = 'my_domain_v2.com'
TEMPLATE_NAME_V2 = 'my_domain_v2'
In the config/database.php
file, I configure the database connections as following.
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '1234'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'unix_socket' => env('DB_SOCKET'),
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST_V2', '127.0.0.1'),
'port' => env('DB_PORT_V2', '5678'),
'database' => env('DB_DATABASE_V2'),
'username' => env('DB_USERNAME_V2'),
'password' => env('DB_PASSWORD_V2'),
'unix_socket' => env('DB_SOCKET'),
],
]
I create the ConfigServiceProvider
class in App\Providers
directory as following.
namespace App\Providers;
class ConfigServiceProvider extends ServiceProvider {
public function register() {
$template = null;
$db_connection = null;
if ( isset($_SERVER["SERVER_NAME"]) ) {
switch ($_SERVER["SERVER_NAME"]) {
case env('DOMAIN_NAME_V1'):
$template = env('TEMPLATE_NAME_V1');
$db_connection = env('DB_CONNECTION');
break;
case env('DOMAIN_NAME_V2'):
$template = env('TEMPLATE_NAME_V2');
$db_connection = env('DB_CONNECTION_V2');
break;
default:
$template = env('TEMPLATE_NAME_V1');
$db_connection = env('DB_CONNECTION');
break;
}
}
$config = app('config');
$config->set('template', $template);
$config->set('database.default', $db_connection);
}
}
I did not include how the views
in the resources
directory and how the TemplateServiceProvider
class look like because this question is about configuring multi database connections, depending on the domain name for code based multi sites.
Is this approach a correct way, efficient and a best practice, compared to using DB::connection('connection_name')
in the controller or set the protected $connection = 'connection_name';
in the model? Does it lead to any disadvantages?