Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an instanced web application that uses different databases for every instance but uses the same files.

What I want my application to do on boot:

  1. Get database credentials from master instance table. This instance table is in the default 'mysql' connection that I have defined in app/config/database.php.
  2. Connect to the instance database from that point on (I don't need the master instance database anymore)

I have tried to do this in my App:before() event, but that won't work as I don't have a sessions table in my master database. If I do it before the return array() in database.php it obviously can't connect because it doesn't have the correct master database credentials yet.

Where am I supposed to do this? Should I just disable sessions and do it in my App::before() and then enable sessions after?

like image 293
Basaa Avatar asked Sep 28 '22 04:09

Basaa


1 Answers

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.

like image 76
Ajay Kumar Ganesh Avatar answered Oct 02 '22 15:10

Ajay Kumar Ganesh