[Tip] Connect to multiple databases on the Fly with Lumen

Its not always an easy way to connect to different database if the configuration files does not include any information about it, in older version it was even a tricky one, especially if you have a bit of relationship that you want to use.

Don’t understand from my words that you cant do that, but it was not a direct use of setConnection , from my memory, the setConnection function used to force the connection on the current model only not the children nor any other one that it has a relationship with, when the info for this connection was not part of the database config file.

Things has changed and now in Lumen 5.5 (I didn’t try it with older version), as now you can use the function on to enforce the connection on the Model and any relationship it needs. like the following:

Create a base Model and create a function within called mergeConnections:

Now creating this base function is not required, but am using it to simplify the idea, but with it you will simplify the idea of merging the connection information that you can get from anywhere, in our code here from the database, and merge it with the database connections config array.

once you get all the information you want, you can simply test that you have the correct configuration using app()->config->get('database.connections') after config->set to see if your database connection is there or not, once you got it working correctly, all you have to do is to set the connection using the on function which will return an instance of Illuminate\Database\Eloquent\Builderand you can work with it like normal.

List below the on function:

now once you got it to work, your Model can be something like:

as you can see nothing special here, except that we extended BaseModel not Model now if you are going to use it, it would be like:

as you can see we put the relation after the merge connections function, to make sure that the relationship will use the same connection.



Information! if you noticed any problem please comment on the post so I can look into it, at the end the goal here is to learn from each others.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.