Laravel Change Connection Dynamically

Laravel: connect to databases dynamically

The simplest solution is to set your database config at runtime. Laravel might expect these settings to be loaded from the config/database.php file, but that doesn't mean you can't set or change them later on.

The config loaded from config/database.php is stored as database in Laravel config. Meaning, the connections array inside config/database.php is stored at database.connections.

So you can easily override/change these connections like this:

Config::set("database.connections.mysql", [
"host" => "...",
"database" => "...",
"username" => "...",
"password" => "..."
]);

From there on out, any Eloquent models that use this mysql connection will be using this new database connection config.

I'd recommend doing this in a Service Provider if possible.

Change the Database Connection Dynamically in Laravel

Well you can use the default database for user login and have a new field for the database name. Then whenever you need to query a different database, you can just change your db connection.

Something like this

$someModel = new SomeModel;
$databaseName = "mysql2"; // Dynamically get this value from db
$someModel->setConnection($databaseName);
$something = $someModel->find(1);

You can read more about it here.
http://fideloper.com/laravel-multiple-database-connections

Laravel Change Connection Dynamically

I will go for a helper here. Let's create one in app/Helpers/DatabaseConnection.php.

namespace App\Helpers;
use Config;
use DB;

class DatabaseConnection
{
public static function setConnection($params)
{
config(['database.connections.onthefly' => [
'driver' => $params->driver,
'host' => $params->host,
'username' => $params->username,
'password' => $params->password
]]);

return DB::connection('onthefly');
}
}

And now somewhere in controller we try

use App\Helpers\DatabaseConnection;
...

$params = Database::find( 1 );
$connection = DatabaseConnection::setConnection($params);
$users = $connection->select(...);

Note: Not tested. I hope it works or simply guide you

More info:

  • Using multi database: https://laravel.com/docs/5.3/database#read-and-write-connections

  • Setting configurations on the fly: https://laravel.com/docs/5.3/configuration#accessing-configuration-values

Dynamic Database change in Laravel

You'll need to purge the cache of the database object:

// Will disconnect automatically
DB::purge('mysql');

// Register new config
Config::set('database.connections.mysql', $config);

// Will reconnect automatically
DB::table('table')->get();

How to append connection dynamically in database.php file in laravel

It is working for me
When I create a new customer then

public function setConnection($tenantName){
//GET Database Connection file path
$path = config_path('database.php');
//GET Database Connection file
$arr = include $path;
// load the array from the file
$new_connection=[
'driver' => 'mysql',
'host' => env('DB_HOST'),
'database' => $tenantName,
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false
];
// modify the array
$arr['connections'][$tenantName]=$new_connection;
// write it back to the file
file_put_contents($path, "<?php return " . var_export($arr, true) . ";");
}

Connect multiple databases dynamically in laravel

One way of changing the connection at runtime is to set the values via the config:

config(['database.connections.mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'my_database'),
'username' => env('DB_USERNAME', 'my_user'),
'password' => env('DB_PASSWORD', 'my_password'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
]]);

This can be applied in a middleware to dynamically switch between tenant databases, for example.

You can also specify a connection via the DB facade:

DB::connection('mysql_2')->select(...);


Related Topics



Leave a reply



Submit