I am trying to create dynamic database connection for each of my models so I can pass a connection name using $model->setConnection('connection_name)
I've tried loads of answers to similar questions but nothing works
I have created a class which creates a new database connection and adds it the database config
<?php
namespace App;
use Illuminate\Support\Facades\Config;
class Clientdb
{
public $connection;
public function __construct($dbUser, $dbPassword, $dbName)
{
Config::set('database.connections.' . $dbUser, array(
'driver' => 'mysql',
'host' => '55.55.55.55',
'port' => '3306',
'database' => $dbName,
'username' => $dbUser,
'password' => $dbPassword,
'unix_socket' => '',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
\PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
));
$this->connection = $dbUser;
}
public function connection() {
return $this->connection;
}
}
In my controller I create a new instance of my new class to add to the database config, then I create a new instance of my model and I pass the connection name to my model setConnection() function.
$this->clientdb = new Clientdb($dbUser, $dbPassword, $dbName);
$model = new \App\MyModel();
// dd($this->clientdb->connection);
$model->setConnection($this->clientdb->connection);
// dd($model);
$result = $model::where('id', $id)->first();
The problem is it still tries to use the connection that is set in the model and the connection is not updated. If I hard code the new connection name in my model it works but I need to make the connections dynamic as I don't want to keep adding to the database config manually.
What an I missing to update the connection in the model.
This is an example of my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'my_table';
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'mysql';
}
sdfsf