Support the ongoing development of Laravel.io →
Database Eloquent

I'm trying to integrate a new Laravel app with an legacy application. That's why I'm in need to use two databases/connections.

Specified my default connection in app/config/database

'default' => 'connection-one',

A normal one-to-one relation across two databases is working as expected.

But when I'm trying to use a many-to-many relationship Laravel is using the wrong database.

models/Member.php

class Member extends Eloquent
{
	protected $connection = 'connection-two';
	protected $primaryKey = 'id_member';
	protected $table = 'legacy_members_table';
	
	public function topics()
	{
		return $this-->belongsToMany('Topic');
	}
}

models/Topic.php

class Topic extends Eloquent
{
	protected $primaryKey = 'token';
	
	public function members()
	{
		return $this->belongsToMany('Member');
	}	
}

Laravel is searching for the correct pivot table member_topic but does this in the old databse with connection-two and not in the new database with connection-one

Is there a way to achieve this ?

The only solution currently on my mind is to use a view in the 'new' database that will use/mimic the data from the table in the old database.

Last updated 3 years ago.
0

Using 'legacy_db' as an example of the actual name for your old database, would this work?

class Topic extends Eloquent
{
    protected $primaryKey = 'token';

    public function members()
    {
        $relation = $this->belongsToMany('Member');
        $relation->table = 'legacy_db.legacy_members_table';
        return $relation;
    }   
}
Last updated 3 years ago.
0
Last updated 3 years ago.
0

OK, I figured it out (after some sleep). Thanks @thevelement to point me into the right direction.

Simply specify [database].[table_name] as the second argument of the relation

class Topic extends Eloquent
{
    protected $primaryKey = 'token';

    public function members()
    {
        retrun $this->belongsToMany('Member','legacy_db.legacy_members_table');
    }   
}
Last updated 3 years ago.
0

Was this really resolved? Are you truly using two distinct servers or just two different schemas?

Last updated 3 years ago.
0

I am still unable to do this across two server connections (vs two schemas).

0

You can do it across multiple server connections with Eloquent. It can get tricky when trying to query through Fluent.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.