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.
Specify Connection
Now that we have a 2nd database connection setup - how do we use it in code?
Schema
Within the Schema Builder, you can use the Schema facade with any connection. To specify which connection to use, simply run the connection() method:
Query
Similar to Schema Builder, you can define a connection on the Query Builder:
Eloquent
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, butRead more