2015-02-09 210 views
4

用户首次运行我的应用程序时,我想设置数据库的详细信息,由用户在我的应用程序中输入。在Laravel动态编辑config/database.php文件

请让我知道如何编辑Laravel中的config/database.php文件并更新用户提供的数据库凭据。

'connections' => array(

    'mysql' => array(
     'driver' => 'mysql', 
     'host'  => '*********', 
     'database' => '********', 
     'username' => '********', 
     'password' => '*******', 
     'charset' => 'utf8', 
     'collation' => 'utf8_unicode_ci', 
     'prefix' => '', 
    ), 
), 
+0

您打算如何为每个用户做到这一点?每个用户是否都有自己的应用程序副本 - 或者全部在一台服务器上? – Laurence 2015-02-09 09:14:33

回答

8

最简单的解决方案可能是在初始配置文件中使用占位符:

'mysql' => array(
    'driver' => 'mysql', 
    'host'  => '%host%', 
    'database' => '%database%', 
    'username' => '%username%', 
    'password' => '%password%', 
    'charset' => 'utf8', 
    'collation' => 'utf8_unicode_ci', 
    'prefix' => '', 
), 

然后就是与实际值进行替换:

$path = app_path('config/database.php'); 
$contents = File::get($path); 

$contents .= str_replace('%host%', $host, $contents); 
// and so on 

File::put($path, $contents); 

这样,你不”不得不实际解析文件。

您可能还想使用某种默认的database.php.dist,并在填写值时创建实际的database.php。这样您就可以使用原始的.dist文件重复设置过程。

+0

谢谢你的工作 – 2015-02-09 09:25:42

+0

我也想要做同样的事情。我已经在app/config中创建了database.php.dist和database.php,但它不起作用。请帮助我做到这一点。 – 2017-04-11 12:55:14

0

没有内置的功能来做你想要的。然而,我自己也做了类似的事情,我只是加载文件,做一个字符串替换操作,然后写回去。顺便说一下,这是laravel自己的方式'set application key' command works,所以至少我们不会丢失任何未公开的功能!

这样的事情,在你的命令的fire方法:

$dialog = $this->getHelperSet()->get('dialog'); 

$host = $dialog->ask($this->output, '<question>Hostname?</question> '); 
$db = $dialog->ask($this->output, '<question>Database?</question> '); 
$user = $dialog->ask($this->output, '<question>Username?</question> '); 
$pass = $dialog->ask($this->output, '<question>Password?</question> '); 

if ($file = file_get_contents(app_path('config/database.php')) { 
    $file = str_replace("'host'  => '*********'", "'host'  => '".$host."'", $file); 
    $file = str_replace("'database' => '********'", "'database' => '".$db."'", $file); 
    $file = str_replace("'username' => '********'", "'username' => '".$user."'", $file); 
    $file = str_replace("'password' => '*******'", "'password' => '".$pass."'", $file); 

    file_put_contents(app_path('config.database.php')); 
} 
1

如果要动态地只是一个要求你也可以使用下面的选项设置数据库连接。

Config::set('database.connections.local.host', '<New Host IP>'); 
Config::set('database.connections.local.database', '<New DB>'); 
Config::set('database.connections.local.username', '<New Username>'); 
Config::set('database.connections.local.password', '<New Password>'); 

您的数据库配置可以看起来像这样在这种情况下,或者只是提供默认的连接信息,并通过上述命令将其覆盖。

'connections' => array(
    'local' => array(
     'driver' => 'mysql', 
     'host'  => '', 
     'database' => '', 
     'username' => '', 
     'password' => '', 
     'charset' => 'utf8', 
     'collation' => 'utf8_unicode_cli', 
     'prefix' => '', 
    ), 
),