Dynamic Blinkie Text Generator at TextSpace.net

Feedburner

I heart FeedBurner

Selasa, 28 November 2017

Koneksi 2 database di laravel

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.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
 
class TestController extends Controller
{
 
    public function getTest()
    {
        $db_ext = \DB::connection('mysql_external');
        $countries = $db_ext->table('countries')->get();
        print_r($countries);
    }
 
}
 

Sumber:http://laraveldaily.com/multiple-database-connections-in-the-same-laravel-project/

Tidak ada komentar:

Posting Komentar