Answer the question
In order to leave comments, you need to log in
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
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' => '',
),
),
);
<?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);
}
}
$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');
<?php
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
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;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question