ShaunL's avatar

Dynamic db connection for model

Hello all,

Ran into a bit of a road block here, I'm attempting to dynamically define a database connection for a model, however, it is not going very well. I attempted to use:

protected $connect = env('some-connection');

but laravel throws an error because i'm using env().

So I attempted to add it to the constructor for the model:

function __construct()
{

    $this->connection = env('some-connect');

{

it somewhat works, however, it only passes primary key and date stamps when I create a new model and no other data.

Anyone have some thoughts on why this would be an issue?

0 likes
2 replies
ShaunL's avatar
ShaunL
OP
Best Answer
Level 5

figured it out, just wanted to post if anyone else has issues with this in the future. Really silly error but my child constructor was overwriting my parent constructor, hence the problem with the parameters being passed. I've confirmed that the below fix will correct it:

  public function __construct(array $attributes = array())
  {

    parent::__construct($attributes);

    $this->setConnection(env('DB_MODE'));

  }
6 likes
coedycode's avatar

Thanks this helped me get over the same problem.

One word of caution to anyone else finding this, don't use env() anywhere except in config files, if config:cache is used in production env() only works in config files.

So here you might create a key called 'mode' in the config/database.php file and assign env('DB_MODE') to that.

Then you can use

$this->setConnection(config('database.mode'));

1 like

Please or to participate in this conversation.