Modify the config / database.php file dynamically in Laravel

advertisements

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 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.

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.