Laravel Eloquent eager loading on a different connection

Solution:

Well, as 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 connection 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();
    DB::setPdo($secondary);
    $result = MyModel::with('AnotherModel')->get();
    DB::setPdo($default);

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.