Seldom there is a situation where we have our project database, but we need to take some external data from another database – for example, using 2 database connections.
if your application has to pull data from 2 MySQL databases, you can define them both separately:
We have our default connection still set to MySQL. This means that, unless we specify otherwise, the application will use the MySQL connection.
Now that we have a 2nd database connection setup - how do we use it in code?
Within the Schema Builder, you can use the Schema facade with any connection. To specify which connection to use, simply run the connection() method:
Similar to Schema Builder, you can define a connection on the Query Builder:
You can also define which connection to use in your Eloquent models as well!
One way is to set the $connection variable in your model:
You can also define the connection at runtime via the setConnection method.
Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.