V
V
Vit2016-08-01 18:00:44
Laravel
Vit, 2016-08-01 18:00:44

How to deal with multiple DB connections?

In the admin panel, you need to switch to remote mysql databases. Is it possible to store settings for connecting to remote databases in the main database table?
All examples of working with several databases come down to writing settings manually in the app/config/database.php
file. The number of databases will increase and I would like to add settings from the admin panel, and not by hand to the file. Tell me how to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrzej Wielski, 2016-08-01
@reech

Store databases in config.
And so, your database.php config looks something like this:

<?php
return array(

    'default' => 'mysql',

    'connections' => array(

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

    ),
);

In connections, you need to add the data of the new database.
Sample helper code for working with configs ( app/helpers/ConfigHelper.php ):
<?php
namespace App\Helpers;
use Illuminate\Config\FileLoader;

class ConfigHelper
{
    static public function save($items, $config, $addon = '')
    {
        $path = base_path()."/config/{$addon}";
        $file = "{$path}/{$config}.php";
        \File::put($file, '<?php return ' . var_export($items, true) . ';');
    }

    static public function drop($config, $addon = ''){
        $path = base_path()."/config/{$addon}";
        $file = "{$path}/{$config}.php";
        \File::delete($file);
    }
}

Example code for creating a new connection:
$database = config('database');
$database['connections']['mysql2'] = array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        );
\App\Helpers\ConfigHelper::save($database, 'database');

To work with a new connection, it is enough to set the connection parameter in the model
<?php

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

Or use "hot" setting:
Schema::connection('mysql2')->create('some_table', function($table)
{
    $table->increments('id'):
});

<?php

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2');

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

        return $something;
    }

}

Etc. Similarly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question