1

How to populate new tables from data in old database tables using laravel?Both database have diffrent structure. Is it possible using Laravel seeding?

2 Answers 2

4

You can use multiple database connections in laravel to connect to both databases.

config/database.php

return [
    'connections' => [
        'old_db' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST_OLD'),
            'database'  => env('DB_DATABASE_OLD'),
            'username'  => env('DB_USERNAME_OLD'),
            'password'  => env('DB_PASSWORD_OLD'),
        ],
        'new_db' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST'),
            'database'  => env('DB_DATABASE'),
            'username'  => env('DB_USERNAME'),
            'password'  => env('DB_PASSWORD'),
        ],
    ],
];

Then in your seed file you can connect to your old database and loop through those items and insert them in your new database

UserTableSeeder.php

$users = DB::connection('old_db')->table('users')->get();

foreach($users as $user){
    DB::connection('new_db')->table('users')->insert([
        'name' => $user->username, //different fieldnames
        'email' => $user->emailaddress, //different fieldnames
    ]);  
}
Sign up to request clarification or add additional context in comments.

Comments

0

If I were You and I needed FAST one time solution, I would:

Get data from old table using DB facade:

 $rows = DB::table('users')->get();    

Structure my foreach something, which works in database seeder and echo it:

foreach ($rows as $row) {
  echo("DB::table('table')->insert(array(
    'name' => '$row->name',
    'email' => '$row->email'
  ));
  <br />");
}

Copy&paste it into database seeder and run it OR structure statemens below to work directly in MySQL and run it in MySQL. It looks stupid, but very fast and works.

Code lines above aren't tested, written from memory.

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.