6

I want to copy an eloquent model from one connection to another.

The way I have done this so far is as so:

$users = User::on('connection1')->where('tenant', 'foo')->get();
User::on('connection2')->insert($users->toArray());

This works most of the time. But there are cases where this does not work. For example:

  • When the model has $hidden attribute
  • When the toArray method for a model is overrided

What is a reliable way to simply copy over some rows to another connection?

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

2 Answers2

1

i think i have found a solution for $hidden attribute & overwriting toArray method

 $users = User::on('connection1')->where('tenant', 'foo')->get();

foreach ($users as $user) {
            $usersArray[] = $user->getAttributes();
        }
User::on('connection2')->insert($usersArray);

if you are using mySql i recommend using bulk insert:

https://www.geeksengine.com/database/data-manipulation/bulk-insert.php

OMR
  • 11,736
  • 5
  • 20
  • 35
0

You can leverage the setConection() method on the eloquent model like so:

$users = User::on('connection1')->where('tenant', 'foo')->get();
foreach ($users as $user) {
   $user->setConnection('connection2');
   $user->save();
}

I found this in another stackoverflow question here

PtrTon
  • 3,705
  • 2
  • 14
  • 24