uxweb
4 years ago
1124
27
General

Change database name of connection on the fly

Posted 4 years ago by uxweb

Hi friends!.

I am working on a new application that must connect to several databases. The number of databases are huge and in some point the models of my app should point to some of this databases.

My first approach will be to define n connections per database in my database.php configuration file, but i think this is not really good cause there are already like 150 databases and often a new one is created, having me to edit the file to add a new connection.

Fortunately there is a database which keeps a list of all the databases, think i can create a model that points to that table and one connection for that.

That will let me present to the user a list of all the databases that exists, and then let the user choose one database that will be the context under all the models will work, i can create another configuration connection for this purpose and change only the database name on the fly according to the database the user has selected.

I think this is pretty much like the tenant app, but is not equal, think this should be more simple.

I think about the on method provided by Eloquent Model, but cause i am not defining every single connection for every single database (which will be a mess) i canĀ“t use it.

Currently i can store the database name in session, what i cant figure out how to do is to tell eloquent models to operate on that database.

Any help will be appreciated.

Thank you!!

Please sign in or create an account to participate in this conversation.