mercredi 15 juin 2016

Multiple database connections in the same Laravel project

In my recent project I need to collect some data from another database.So I need to connect with that database with my existing database server. For that I have done the following procedure.

First I change the configuration in config/database.php file, I have written the second connection in connection array like this:

'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,
            'engine'    => null,
        ],


/*This is my Second Connection*/
        '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,
    ],

Then I change the .env file also.

APP_ENV=local
APP_DEBUG=true
APP_KEY=PZ0tReA5jAEQmi47PGoe5Adinp46kxTQ

DB_HOST=localhost
DB_DATABASE=5.2
DB_USERNAME=root
DB_PASSWORD=

DB_EXT_HOST=localhost
DB_EXT_DATABASE=acl
DB_EXT_USERNAME=root
DB_EXT_PASSWORD=

CACHE_DRIVER=file
SESSION_DRIVER=file

Then in controller I connect the second database with the following code:

public function getTest()
   {
    $db_ext = \DB::connection('mysql_external');    
    $user = $db_ext->User::all();
    print_r($user);
  }

But I'm getting following Error:

InvalidArgumentException in DatabaseManager.php line 239:
Database [mysql_external] not configured.

If anyone can help me find to find the problem, it'll be very helpful.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire