Get database credentials from master database, then connect to different database Get database credentials from master database, then connect to different database laravel laravel

Get database credentials from master database, then connect to different database


Don't think its possible, But here is a possibility.

Read / Write Connections

Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM.

To see how read / write connections should be configured, let's look at this example:

'mysql' => array(    'read' => array(        'host' => '192.168.1.1',    ),    'write' => array(        'host' => '196.168.1.2'    ),    'driver'    => 'mysql',    'database'  => 'database',    'username'  => 'root',    'password'  => '',    'charset'   => 'utf8',    'collation' => 'utf8_unicode_ci',    'prefix'    => '',),

Note that two keys have been added to the configuration array: read and write. Both of these keys have array values containing a single key: host. The rest of the database options for the read and write connections will be merged from the main mysql array. So, we only need to place items in the read and write arrays if we wish to override the values in the main array. So, in this case, 192.168.1.1 will be used as the "read" connection, while 192.168.1.2 will be used as the "write" connection. The database credentials, prefix, character set, and all other options in the main mysql array will be shared across both connections.


After some hours of experimenting and trying I have found out that the best option really is to create a PDO instance manually in the /app/config/database.php file and get the database credentials that way:

// Get instance row    if (!App::runningInConsole() && !array_key_exists('instance_found', $_ENV)) {        $conn = new PDO('mysql:dbname=instances;host=127.0.0.1', 'root', 'password');        $stmt = $conn->prepare('SELECT * FROM instances WHERE http_host=?');        $stmt->bindParam(1, $_SERVER['HTTP_HOST']);        $stmt->execute();        $instance = $stmt->fetch(PDO::FETCH_OBJ);        $conn = null;        if (!$instance) {            return Response::make('Whoops!', 404);        } else {            $_ENV['instance_found'] = true;            $database = $instance->mysql_database;            $username = $instance->mysql_username;            $password = $instance->mysql_password;        }    }