Multiple schemas in the Laravel database 5

7

Good afternoon, I'm redoing a system and I adopted Laravel 5. In this system I have several schemas in the database and the solution I found was to work with a connection for each schema, as follows:

'pgsql' => [
            'driver'   => 'pgsql',
            'host'     => env('DB_HOST', 'localhost'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'schema1',
        ],

        'pgsql2' => [
            'driver'   => 'pgsql',
            'host'     => env('DB_HOST', 'localhost'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'schema2',
        ],

Would you have any other way to do this?

    
asked by anonymous 25.08.2015 / 21:34

1 answer

7

The best way to work with multiple banks in laravel is this way:

In the configuration file you can define all the drivers to be used and the banks:

return array(

'default' => 'mysql',

'connections' => array(

    # Our primary database connection
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'host1',
        'database'  => 'database1',
        'username'  => 'user1',
        'password'  => 'pass1'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

    # Our secondary database connection
    'mysql2' => array(
        'driver'    => 'mysql',
        'host'      => 'host2',
        'database'  => 'database2',
        'username'  => 'user2',
        'password'  => 'pass2'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
  ),
);

After this you will have to define in your models which connection to use, for example in the use of Eloquent it will be possible to configure only by defining in the scope of the class:

protected $connection = 'mysql2';

In this way all queries / changes will be made through the mysql2 settings.

It is also possible to define the connection outside the class, but within the scope of the function, that is, when you want to execute X function in Y database:

public function method()
{
    $this->setConnection('mysql2');

    $this = $someModel->find(1);

    return $something;
}

You can also work off eloquent this way:

$users = DB::connection('mysql2')->select(...);

So your system is ready to receive multi-connections. Show, right?

Hugs!

Sources: link

    
11.09.2015 / 20:44