How to Make Multiple database connections in the same Laravel project?
Sometimes there could be a situation where we have our main project database, but we have to depend on/ need some external data from another database. So we need to configure the other database with the existing database. In real life example such as Blog. It could be maintained by 3rd party software. So in that situation we need to use the external data source to sync with the existing one. Let's stop the chitchat and start the session.
1. First we need to change the configure file
in config/database.php file. Here we gonna add a new database engine configure.
In this tutorial I'm gonna add mySQL server. So add this configuration in connections array.
'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,'engine' => null,],
2. Then in .env file add this lines with the
existing lines.
DB_EXT_HOST=localhostDB_EXT_DATABASE=acl // suppose our new database name is 'acl'DB_EXT_USERNAME=rootDB_EXT_PASSWORD=
3. Now Let’s go to the controller section. Here is
the main part because here you’ll see how you can connect the new database with
the existing one.
public function getTest(){$user = DB::connection('mysql_external')->table('users')->get();print_r($user);}
In this controller we connect the other database
with DB::connection() method which will connect with the other database and
retreive data from that source.
So That’s it for today. Hope you like the session. See you in the next session.
So That’s it for today. Hope you like the session. See you in the next session.
Thank you.
0 comments:
Post a Comment