Pier-Yves Lessard Pier-Yves Lessard - 5 months ago 38x
PHP Question

Laravel Eloquent eager loading on a different connection

I am trying to use Laravel Eloquent ORM to do a simple one to one relationship on another connection.

Let say do :


That is working fine.

When I do :


I am getting an error because eloquent is doing the AnotherModel SELECT statement on the default connection (instead of "secondary_connection").

I can't find a way to work this around.

My models are well defined since I can join them in my default connection.

Thoughts ?


Well I've been suggested by many users, it seems that there's no way to do this on the fly. My understanding of this is that Eloquent is incomplete when comes to manage multi-connection.

There's 2 way to work this around I could figure.

First, specify the conenction in the model :

class MyModel {
    $protected connection = 'secondary_connection';

That is obviously a bad workaround since this model is only usable in one connection... but still works.

Then, as Jarek Tkaczyk suggested, it is possible to switch de default connection with the new one. But instead of doing it in the config file, it is possible to swap the PDO oject.

    $default = DB::getPdo(); // Default conn
    $secondary = DB::connection('secondary_connection')->getPdo();
    $result = MyModel::with('AnotherModel')->get();

That is a workaround that works and can be a clean solution. Next step is to put that switching mechanism in a nice Laravel way.