Multiple database connections in the same Laravel project

Sometimes there is a situation where we have our main project database, but we need to take some external data from another database – for example, where blog is stored, managed by 3rd party software. How to handle it in Laravel 5?

Where to put database credentials

There is a file config/database.php which contains an array of all possible connections- MySQL, PostgreSQL, SQL Server. So the “trick” here is we can add more than one connection with the same database system, let’s say it will be MySQL. So, let’s copy a default array item and paste as another one underneath – and call it mysql_external:

Now, let’s change the ENV variables to different ones, which we will add into our .env file. For example, from DB_HOST – to DB_EXT_HOST and same with others.

And now we have two options: provide those external credentials here in the same config/database.php file, or add them into .env file, which is in your main Laravel folder, like this:

How to connect to the second database

So, we have a connection named mysql_external which has the credentials provided, now we can actually use it. So in your code, where you need to take the data from that external database, you just call DB::connection() method and assign the result to the variable. Then we can use that variable to make any queries.

And that’s it, basically. You can then use any DB functions to get or insert the data into your external database.

Check out my new online course: Creating Invoices with Laravel 5.6