3

I can see how to have multiple connections using a configuration file in app/config/database.php and this is well documented.

Is this the only way or can you also define multiple connections using the .env file?

HamptonNorth
  • 549
  • 7
  • 13
  • 1
    Thanks for this detailed and clear response. This is how I'd already coded the multiple databases problem as per the docs. The key missing bit is still "can you also define multiple connections using the .env file?" – HamptonNorth Mar 05 '16 at 11:19

1 Answers1

3

First, you'll need to configure your connections. You need to create a config directory in your project and add the file config/database.php. Like this:

<?php
return [

    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'homestead',
            'username'  => 'root',
            'password'  => 'secret',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
        'mysql2' => [
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'homestead2',
            'username'  => 'root',
            'password'  => 'secret',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
    ],

Once you've added your connection configurations, you can access them by getting the database manager object out of the container and calling ->connection('connection_name'). See below for a full example.

<?php
namespace App\Http\Controllers;
use Illuminate\Database\DatabaseManager;
class StatsController extends Controller
{
    /**
     * @return array
     */
    public function getLatest()
    {
        // Resolve dependencies out of container
        /** @var DatabaseManager $db */

        $db = app('db');
        $database1 = $db->connection('mysql');
        $database2 = $db->connection('mysql2');

        // Look up 3 newest users and 3 newest blog posts
        $threeNewestUsers = $database1->select("SELECT * FROM users ORDER BY created_at DESC LIMIT 3");

        $threeLatestPosts = $database2->select("SELECT * FROM blog_posts ORDER BY created_at DESC LIMIT 3");
        return [
            "new_users" => $threeNewestUsers,
            "new_posts" => $threeLatestPosts,
        ];
    }
}

http://andyfleming.com/configuring-multiple-database-connections-in-lumen-without-facades/

plcosta
  • 345
  • 4
  • 9