Tip Connect to multiple databases on the Fly with Lumen
Published 3 years and 10 months ago, Categorized under: Code, Laravel, PHP

Its not always an easy way to connect to different database if the configuration files does not include any information about it, in older version it was even a tricky one, especially if you have a bit of relationship that you want to use.

Don't understand from my words that you cant do that, but it was not a direct use of setConnection , from my memory, the setConnection function used to force the connection on the current model only not the children nor any other one that it has a relationship with, when the info for this connection was not part of the database config file.

Things has changed and now in Lumen 5.5 (I didn't try it with older version), as now you can use the function on to enforce the connection on the Model and any relationship it needs. like the following:

Create a base Model and create a function within called mergeConnections:


namespace App\Models;

use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
    public function mergeConnections($connectionName)
        $connection = app()
            ->where('db_name', $connectionName)

            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'port'      => env('DB_PORT', 3306),
            'database'  => $connection->db_name,
            'username'  => $connection->db_user,
            'password'  => Crypt::decrypt($connection->db_password),
            'charset'   => env('DB_CHARSET', 'utf8'),
            'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
            'prefix'    => env('DB_PREFIX', ''),
            'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),

        $fullConnections = array_merge(config('database.connections'), $connections);

        app()->config->set('database.connections', $fullConnections);

        return $this->on($connectionName);

Now creating this base function is not required, but am using it to simplify the idea, but with it you will simplify the idea of merging the connection information that you can get from anywhere, in our code here from the database, and merge it with the database connections config array.

once you get all the information you want, you can simply test that you have the correct configuration using app()->config->get('database.connections') after config->set to see if your database connection is there or not, once you got it working correctly, all you have to do is to set the connection using the on function which will return an instance of Illuminate\Database\Eloquent\Builderand you can work with it like normal.

List below the on function:

     * Begin querying the model on a given connection.
     * @param    string|null  $connection
     * @return  \Illuminate\Database\Eloquent\Builder
    public static function on($connection = null)
        // First we will just create a fresh instance of this model, and then we can
        // set the connection on the model so that it is be used for the queries
        // we execute, as well as being set on each relationship we retrieve.
        $instance = new static;
        return $instance->newQuery();

now once you got it to work, your Model can be something like:


namespace App\Models;

class User extends BaseModel
    public function address()
        return $this->hasOne(Address::class)

as you can see nothing special here, except that we extended BaseModel not Model now if you are going to use it, it would be like:


As you can see we put the relation after the merge connections function, to make sure that the relationship will use the same connection.

PS: if you noticed any problem please comment on the post so I can look into it, at the end the goal here is to learn from each others.

Share It via: