Laravel动态改变env值

时间:2017-12-27 07:10:10

标签: php laravel-5 installation

我正在使用Brotzka Env Editor。我正在创建一个页面来连接到新创建的数据库。在我的.env中我有这个值

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=xxx
DB_USERNAME=root
DB_PASSWORD=

我设法通过运行此代码将DB_DATABASE和DB_PASSWORD分别更改为SHOP和P @ ssw0rd

$env = new DotenvEditor();
$env->changeEnv([
   'DB_HOST' => $request['hostname'],
   'DB_DATABASE' => $request['dbname'],
   'DB_USERNAME' => $request['username'],
   'DB_PASSWORD' => $request['dbpassword'],
]);

 $exitCode = Artisan::call('config:clear');
 $exitCode = Artisan::call('cache:clear');

 DB::connection()->getPdo();

但是在DB:connection() - getPdo()行我遇到了像

这样的错误
[2017-12-27 06:42:15] local.ERROR: exception 'PDOException' with message 'SQLSTATE[HY000] [1045] Access denied for user 'XXXXX'@'localhost' (using password: NO)' in C:\alaracart\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOConnection.php:43

仍然是旧的.env值。什么可能是'重置'命令重新加载laravel?感谢。

1 个答案:

答案 0 :(得分:0)

您需要更改问题“动态更改默认数据库连接” 这就是答案,但它会解决你的问题。

更改当前请求或流程中的env值无效。如果你需要更改直接配置值。

例如,在请求时更改当前数据库连接数据库名称。

//get old dbname
$oldDbName = env("DB_DATABASE");


$env = new DotenvEditor();
$env->changeEnv([
   'DB_HOST' => $request['hostname'],
   'DB_DATABASE' => $request['dbname'],
   'DB_USERNAME' => $request['username'],
   'DB_PASSWORD' => $request['dbpassword'],
]);

DB::disconnect(env("DB_CONNECTION"));

Config::set('database.connections.' . env("DB_CONNECTION"), array(
        'driver'    => 'mysql', //or $request['driver'],
        'host'      => $request['hostname'],
        'database'  => $request['dbname'],
        'username'  => $request['username'],
        'password'  => $request['dbpassword'],
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix'    => '',
));

//Trying reconnect database
try {
        DB::connection()->getPdo();
    } catch (\Exception $e) {
        //revert old db if any error
        DB::disconnect(env("DB_CONNECTION"));
        Config::set('database.connections.' . env("DB_CONNECTION") .'.database', $oldDbName );
    }

有用的链接: https://laracasts.com/discuss/channels/general-discussion/l5-change-default-database-connection-dynamically?page=1