Laravel 5 Polymorphic in multiple connection

I am trying to establish a polymorphic relationship with several databases when connecting.

Say I have

  • Database A, User Table (id, email, password, userable_id, userable_type)
  • Database B, Company table (identifier, name, address, telephone)

In each user and company model, I also establish each connection:

/* Database A */
protected $connection = 'database_a';

/* Database B */
protected $connection = 'database_b';

And for the relationship

/* Database A (User model) */
public function userable()
{
    return $this->morphTo();
}

/* Database B (Company Model) */
public function user()
{
    return $this->morphMany('user','userable');
}

And in my AppServiceProvider.php, I morphMap the user and provider models:

Relation::morphMap([
    'user' => \App\Models\V1\Shared\User::class,
    'vendor' => \App\Models\V1\Training\Vendor::class       
]);

This code will not work if I have not established the user relation to the connection:

public function userable()
{
    return $this->setConnection('database_b')->morphTo();
}

, , , / laravel morphTo setConnection()?

+4

All Articles