在Laravel中动态编辑config/database.php文件 [英] Dynamically edit config/database.php file in Laravel

查看:74
本文介绍了在Laravel中动态编辑config/database.php文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户第一次运行我的应用程序时,我想设置用户在我的应用程序中输入的数据库详细信息.

First time when user runs my application i want to set database details as entered by the user in my application.

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

Please let me know how i can edit config/database.php file in Laravel and update database credentials as provided by user.

'connections' => array(

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

推荐答案

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

The simplest solution is probably to use placeholders in the initial config file:

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

然后将它们替换为实际值:

And then just replace them with the actual values:

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

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

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

通过这种方式,您不必真正解析文件.

This way you don't have to actually parse the file.

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

You might also want to use some kind of default database.php.dist and create the actual database.php when filling in the values. This way you could always repeat the set up process by using the original .dist file.

这篇关于在Laravel中动态编辑config/database.php文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆