在Laravel中动态编辑config/database.php文件

6

当用户第一次运行我的应用程序时,我希望将数据库细节设置为由用户在应用程序中输入的内容。

请告诉我如何在Laravel中编辑config / database.php文件,并根据用户提供的内容更新数据库凭据。

'connections' => array(

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

1
你是否计划为每个用户都做这个?每个用户是否有自己的应用程序副本,还是所有应用程序都在一个服务器上? - Laurence
3个回答

12

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

'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文件来重复设置过程。


我也想做同样的事情。我已经在app/config中创建了database.php.dist和database.php文件,但它没有起作用。请帮助我完成这个任务。 - Sagar Arora

4

如果您想为仅 一个 请求动态设置数据库连接,您还可以使用以下选项。

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>');

如果是这种情况,您的DB配置可能如下所示,或者只需提供默认连接信息,并通过以上命令进行覆盖。
'connections' => array(
    'local' => array(
        'driver'    => 'mysql',
        'host'      => '',
        'database'  => '',
        'username'  => '',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_cli',
        'prefix'    => '',
     ),
),

嗨,我有一个问题。一旦我们为当前运行时设置了配置,它将持续整个请求生命周期,对吧?那么,如果需要动态设置配置文件的请求被安排为稍后执行的作业,那么更改的配置是否会持久化? - Aadesh Dhakal

0

这里没有内置的功能来实现你想要的。不过,我自己做过类似的事情,我只是加载文件,进行字符串替换操作,然后再写回去。顺便说一下,这也是 Laravel 自己的 '设置应用密钥' 命令的工作方式,所以至少我们没有错过任何未记录的功能!

在你的命令的 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'));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接