Dynamically edit config/database.php file in Laravel

前端 未结 3 499
温柔的废话
温柔的废话 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:20

    There's no built-in functionality to do what you want here. However, I have done a similar thing myself and I just load the file in, do a string replacement operation and then write it back out. This, by the way, is the way that laravel's own 'set application key' command works, so at least we aren't missing any undocumented functionality!

    Something like this, in your command's fire method:

    $dialog = $this->getHelperSet()->get('dialog');
    
    $host = $dialog->ask($this->output, 'Hostname? ');
    $db   = $dialog->ask($this->output, 'Database? ');
    $user = $dialog->ask($this->output, 'Username? ');
    $pass = $dialog->ask($this->output, 'Password? ');
    
    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'));
    }
    

提交回复
热议问题