Dynamically edit config/database.php file in Laravel

前端 未结 3 503
温柔的废话
温柔的废话 2021-02-06 14:29

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

Please let me know how i can edit config/database.php f

3条回答
  •  梦谈多话
    2021-02-06 15:13

    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.

    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.

提交回复
热议问题