Laravel environment config not loading, migration

2019-08-06 19:44发布

问题:

My app/config/database.php has been setup like this:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => getenv('DB_HOST'),
    'database'  => getenv('DB_NAME'),
    'username'  => getenv('DB_USER'),
    'password'  => getenv('DB_PASS'),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

I have updated my env detection code like this in bootstrap/start.php:

$env = $app->detectEnvironment(function() {
    return file_exists(dirname(__FILE__) . '/../.env.production.php')
        ?
        'production'
        :
        'local';
});

Now, I have uploaded .env.production.php with the following:

<?php

return
[
    'DB_HOST' => '178.xxx.xxx.xxx',
    'DB_NAME' => 'USERNAME',
    'DB_USER' => 'PASSWORD',
    'DB_PASS' => 'DBNAME',
];

I tested the environment detection like this:

[www-data@server]$ php artisan env
Current application environment: production

As you can see, it's working as intended. I then proceeded to run the migration like this:

php artisan migration:install

When I do, I get the following error:

[www-data@server]$ php artisan migrate:install --env=production

  [PDOException]                                    
  SQLSTATE[HY000] [2002] No such file or directory  

migrate:install [--database[="..."]]

Any idea why this might be? it looks like it's failing to load the .env.production.php file.

Does anyone know how to fix this error? Thanks in advance.

回答1:

In the Laravel 4 docs it states that it needs to be .env.php on your production server.

Now, on your production server, create a .env.php file in your project root that contains the corresponding values for your production environment. Like the .env.local.php file, the production .env.php file should never be included in source control.

So simply change your environment detection code to this

$env = $app->detectEnvironment(function() {
    return file_exists(dirname(__FILE__) . '/../.env.php')
        ?
        'production'
        :
        'local';
});

Note - you still use .env.local.php on your development server.