Actually no there is not other way than setting it in .env becuase even if you want to make it dynamic you have to set like 100 ifs for that if you just want to see 100 settings without writing 100 lines of code you can set a loop in this file :
app/config/database.php
like below :
return array(
'default' => 'mysql',
'connections' => array(
# Primary/Default database connection
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'database1',
'username' => 'root',
'password' => 'secret'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# You loop here
'mysql2' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'database2',
'username' => 'root',
'password' => 'secret'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
thats the easiest way to do that . so here as instructed below and then in your eloquent you should specify what database connection you want to use for that query !! :
You can set in Env file like below :
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret
and then you can go into your condif/database.php and do the setting as below :
'mysql2' => [
'driver' => env('DB_CONNECTION_SECOND'),
'host' => env('DB_HOST_SECOND'),
'port' => env('DB_PORT_SECOND'),
'database' => env('DB_DATABASE_SECOND'),
'username' => env('DB_USERNAME_SECOND'),
'password' => env('DB_PASSWORD_SECOND'),
],
and then in your eloquent you can use as below :
$users = DB::connection('mysql2')->select(...);
Hope this can help you
note :
you can refer to this link for further info
https://fideloper.com/laravel-multiple-database-connections