-1

I want to store multiple database connection in my current laravel db. i need to connect these via dropdown and generate reports on the fly. what is the best way to configure this

2 Answers 2

1

You can just create a table "connection(strings)" in your 1st db and create a model for that table.

After that you can do something like this:

$selected = Connection::query()->where('name', 'fromdropdown')->first();
   $connection = $selected;
                config(['database.connections.data' => array(
                    'driver'    => 'sqlsrv',
                    'host' => $connection['Database_Server'],
                    'database' => $connection['Database_Name'],
                    'username' => $connection['Database_User'],
                    'password' => $connection['Database_Pass']

                )]);

                DB::setDefaultConnection('data');
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry but can you be some more precise how will i perform queries from that connection
Well laravel will always use the default db connection, which we set in the last line :)
0

You can set multiple database connections in the app/config/database.php file.

Example:

'default' => 'mysql',

    'connections' => array(

        # Our primary database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    )

And then just use the connection name in your query:

$users = DB::connection('mysql2')->select(...);

1 Comment

Thanks for your response but i will have to add 15 db connections and more will be added in future so i need to put in the current db.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.