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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
'connections'
=> [
'sqlite'
=> [
// ...
],
'mysql'
=> [
'driver' =>
'mysql',
'host' =>
env('DB_HOST', 'localhost'),
'database' =>
env('DB_DATABASE', 'forge'),
'username' =>
env('DB_USERNAME', 'forge'),
'password' =>
env('DB_PASSWORD', ''),
'charset'
=> 'utf8',
'collation'
=> 'utf8_unicode_ci',
'prefix' =>
'',
'strict' =>
false,
],
'mysql_external'
=> [
'driver' =>
'mysql',
'host' =>
env('DB_HOST', 'localhost'),
'database' =>
env('DB_DATABASE', 'forge'),
'username' =>
env('DB_USERNAME', 'forge'),
'password' =>
env('DB_PASSWORD', ''),
'charset'
=> 'utf8',
'collation'
=> 'utf8_unicode_ci',
'prefix' =>
'',
'strict' =>
false,
],
'pgsql'
=> [
// ...
],
'sqlsrv'
=> [
// ...
],
],
|
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.
1
2
3
4
5
6
7
8
9
10
11
|
'mysql_external'
=> [
'driver' =>
'mysql',
'host' =>
env('DB_EXT_HOST', 'localhost'),
'database' =>
env('DB_EXT_DATABASE', 'forge'),
'username' =>
env('DB_EXT_USERNAME', 'forge'),
'password' =>
env('DB_EXT_PASSWORD', ''),
'charset'
=> 'utf8',
'collation'
=> 'utf8_unicode_ci',
'prefix' =>
'',
'strict' =>
false,
],
|
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:
1
2
3
4
5
6
7
8
9
|
DB_HOST=localhost
DB_DATABASE=testing
DB_USERNAME=homestead
DB_PASSWORD=secret
DB_EXT_HOST=localhost
DB_EXT_DATABASE=testing2
DB_EXT_USERNAME=homestead
DB_EXT_PASSWORD=secret
|
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.
1
2
3
4
5
6
7
8
9
|
class TestController extends Controller
{
public function
getTest()
{
$db_ext
= \DB::connection('mysql_external');
$countries
= $db_ext->table('countries')->get();
print_r($countries);
}
}
|
And that’s it,
basically. You can then use any DB functions to get or insert the data into
your external database.
Comments
Post a Comment