2

I am using Laravel 5.5 and I need to change database dynamically,
For example, there are two databases,db1 and db2,there is a table articles in each database.

Now I want to copy articles from db1 to db2,

in .env file, the current database is db1:

DB_DATABASE=db1

I want to change it dynamically when copying records, I tried to do it like this:

public function test()
{
    $articles=Article::all();

    Config::set("database.connections.mysql", [
        "host" => "127.0.0.1",
        "database" => "db2",
        "username" => "root",
        "password" => ""
    ]);
    //DB::purge('mysql');  //this line exists or not,it has the same error.
    DB::table('articles')->insert($articles);
    dd('ok');
}

but there is an error:

Undefined index: driver

I have many databases, so I don't want to change it in .env file.
What should I do?

update:

in config/database.php it has the two items:

'default' => env('DB_CONNECTION', 'mysql'),

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

],

and I try

    Config::set("database.connections.mysql", [
       'mysql' => [
           "host" => "127.0.0.1",
           "database" => "db2",
           "username" => "root",
           "password" => ""
        ]
    ]);

The error still exists.

5
  • Have you checked 'default' => env('DB_CONNECTION', 'mysql') present in config/database.php ? Commented Sep 6, 2017 at 4:46
  • @Sagar Gautam it has this item. Commented Sep 6, 2017 at 4:54
  • One way is to use DB::connection() with creating a new connection to database. Commented Sep 6, 2017 at 5:01
  • @Sagar Gautam but this way need write database name into config/database.php,I have many datatases. Commented Sep 6, 2017 at 5:06
  • Then it will be a problem to write whole connection over there, Commented Sep 6, 2017 at 5:08

3 Answers 3

6

The error is because you are missing the driver in your configuration.

A better way of changing the connection would be registering your new connection in database configuration file and change the connection at runtime.

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'newConnection' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => 'db2',
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
]

Now you can change your connection using the name you used to define your new connection.

Change the default connection

Config::set('database.default', 'newConnection');
DB::reconnect('newConnection');

or change the connection for a query builder

DB::connection('newConnection')->table('articles')->insert($articles);

or if you are using Eloquent models you can set the default connection associated with the model using the connection property

protected $connection = 'newConnection';

or change at runtime by calling setConnection

(new User)->setConnection('newConnection');

If you wish to change the current connection details you can change them as you wish

Config::set('database.connections.mysql.database', 'db2');

and after changes you need to call

DB::reconnect('mysql');

or

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

1 Comment

Config::set('database.connections.mysql.database', 'db2');it works.
1
public function test()
{
    $articles=Article::all();

    Config::set("database.connections.mysql", [
        "driver" => "mysql"
        "host" => "127.0.0.1",
        "database" => "db2",
        "username" => "root",
        "password" => ""
    ]);
    //DB::purge('mysql');  //this line exists or not,it has the same error.
    DB::table('articles')->insert($articles);
    dd('ok');
}

you were missing the driver , as laravel needs what driver of database you want to use, as you are using database.connection.mysql it will set the values in that array, but still the driver is needed

as for example 


'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),

        ],

7 Comments

I don't understand.the defalut config file has 'driver' => 'mysql',see my update.
you are putting it by yourself bro, thus you need to pass the array key value pair.
I have many databases.Assuming I have 200 databases,thus I will add 200 items.I don't want to do it like this.
what you dont want too?? you are just adding the driver index to your code only, see the upper portion of the ans, i have just added a driver value to your code only, and nothing else
@Exprator I see. I misunderstand.
|
0

In my case driver was configured as well as everything else but it threw that error when I hit any endpoint. I was not able to delete cache with php artisan command so for me solution was to manually delete cache files from app/bootstrap/cache folder as old configuration stayed there and did not recognized new database connection.

Comments

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.