Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 977
Maurice Avatar asked Feb 01 '26 12:02

Maurice


1 Answers

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');
}
like image 174
user1669496 Avatar answered Feb 04 '26 00:02

user1669496



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!