As I begin to create more full featured Laravel packages, I find that I want to offer the ability for users to specify different database credentials for my package than the ones used by default in the Laravel application skeleton in which it is installed. One such instance occured to me when starting to create my FAQ package. So, let's look at how we might do this.

After talking to Taylor, I learned that the trick lies in a method within the Illuminate\Database\Eloquent\Model called getConnection. If you look through the code, we find that all queries lay on top of an Illuminate\Database\Connection. At first, I thought that I would have to inject a bunch properties to create a new Connection. But, then I was schooled in learning that the ConnectionResolver creates connections for any connections within the database.connections array.

So, with this knowledge we can start by adding a database connection to the configuration on the fly.

Within our Service Provider's boot method, we will call $this->setConnection(); to abstract this logic away a bit. And we will create setConnection:

public function setConnection()
{
    $connection = Config::get('laravel-faq::database.default');

    if ($connection !== 'default') {
        $wardrobeConfig = Config::get('laravel-faq::database.connections.'.$connection);
    } else {
        $connection = Config::get('database.default');
        $wardrobeConfig = Config::get('database.connections.'.$connection);
    }

    Config::set('database.connections.faq', $wardrobeConfig);
}

And in our package's src/config/database.php:

return array(
    'default' => 'default',
    'connections' => array(
        'sqlite' => array(
            'driver'   => 'sqlite',
            'database' => app_path().'/database/faq.sqlite',
            'prefix'   => '',
        ),
        // More connections
    ),
    ),
);

This code will look into our configuation and if our default is set to 'default', then our application will grab the host app's default database connection and copy it into the connections array under 'faq'. If the pacakge's database default is set to something else, it will look within those connections and stuff that into the 'faq' connection.

Now that we have a new connection set up, we power all of our packages Models with this new connection. We do so by modifying the getConnection function in a base model. First, create a BaseModel.php in your package:

class BaseModel extends \Illuminate\Database\Eloquent\Model
{
    public function getConnection()
    {
        return static::resolveConnection('faq');
    }
}

When creating models extend from this new BaseModel. All of your connections will run from the faq connection instead of the default. Now we are all setup and more flexible than ever!