Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Laravel 4.2: Copying database records from one database to another

I need to copy a subset of records from one database to another in Laravel 4.2

I've written an artisan task that loads the models that I need to copy from the "default" database connection, and now need to save them to the second database connection (which is defined in config/database.php). What I can't find is any way to use the model's save() method to save to a database other than the default connection.

Is this possible? Can I "push" my saves to the second database connection? Or do I need to change to a "pull" logic, reverse my database connection definitions, and load the data from the "second" connection before saving to the "default"?

like image 495
Mark Baker Avatar asked Oct 30 '22 04:10

Mark Baker

1 Answers

First of all you have to define the secoundary connection in app/conifg/database.php and then in connections for example:

'second_db_conn' => [
        'driver'    => 'mysql',
        'host'      => $_SERVER['MYSQL_HOST'],
        'database'  => $_SERVER['MYSQL_DATABASE'],
        'username'  => $_SERVER['MYSQL_USERNAME'],
        'password'  => $_SERVER['MYSQL_PASSWORD'],
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',

Then set this connection on yout model - save it - and switch back to the default (in my example is a mysql):

like image 101
Filip Koblański Avatar answered Nov 09 '22 14:11

Filip Koblański