Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically edit config/database.php file in Laravel

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'    => '',
    ),
),
like image 624
sujit prasad Avatar asked Feb 09 '15 08:02

sujit prasad


1 Answers

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.

like image 132
lukasgeiter Avatar answered Sep 24 '22 17:09

lukasgeiter