Maurice
Maurice

Reputation: 1362

Laravel 5.1, how to have a dynamic database connection in model

I`m using a self created package. This package includes some models. These models should connect to the APP database, but because its a package, the database names can be different.

To solve this, my package includes a config file, where the database name(connection name) is stored.

In the config file:

return [ 'app_model_db_connection' => 'first_database' ];

This works fine, i can grab the config value by doing: Config::get('myconfig.app_model_db_connection);

Now i wanted to do this in my model:

protected $connection = \Config::get('package_customview.app_model_db_connection');

But this does not work. The error: syntax error, unexpected '(', expecting ',' or ';'

Looks like i can only add a string after $connection = . Because when i do: protected $connection = "first_database" , it works. But i want to grab this value from my config file. Is this somehow possible?

Upvotes: 3

Views: 870

Answers (1)

user1669496
user1669496

Reputation: 33058

Yeah, you'd just have to put it in the constructor of the model.

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);
    $this->connection = \Config::get('package_customview.app_model_db_connection');
}

Upvotes: 1

Related Questions