Skip to content
Advertisement

How to change Eloquent Builder’s connection?

I have a Eloquent Builder and two database connections(mysql_server1, mysql_server2) as below:

$builder = User::query();

$builder->where('age', '>', 20);

$builder->with('orders');

// Change connection name here

$builder->whereNotNull('email');

Now how can I change the connection of $builder?

Any helps would be appreciated

Advertisement

Answer

Need to get the Query from Eloquent Builder and set a new connection to that and set the new query to the Eloquent Builder as below:

$builder = User::query();
$conn = DB::connection('mysql_server2');

$builder->where('age', '>', 20);

$builder->with('orders');

// Magic Happens Here
// Change Connection Here
$query = $builder->getQuery();
$query->connection = $conn;
$query->grammar = $conn->query()->getGrammar();
$query->processor = $conn->query()->getProcessor();
$builder = $builder->setQuery($query);

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement