Stefan Hansch
Stefan Hansch

Reputation: 1590

In seed laravel does not pull from environment variables correctly

In .env following values are set for the user:

APP_ENV=local
APP_KEY=base64:jkUuiJJr7k+TzJwOZUExhJ/Mdr4i3Jg=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my-database
DB_USERNAME=my_user
DB_PASSWORD=123

On a remote server run seeds, gives the following error:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Seeded: SiteStringsTableSeeder ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Seeded: FileGroupsTableSeeder ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) Seeded: AreasTableSeeder PHP Fatal error: Class 'Faker\Factory' not found in /var/www/laravel/bootstrap/cache/compiled.php on line 7885

class SiteStringsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // mysqldump --max_allowed_packet=1G --no-create-info=TRUE --user=root --default-character-set=utf8 "db_old" "sitestring" > db_old_sitestring.sql
        // mysql -uroot my_user < db_old_sitestring.sql
        $pass_if_pass =  env('DB_PASSWORD');
        $pass_if_pass =  $pass_if_pass ? ' -p'.$pass_if_pass.' ' : ' ';


        exec("mysql -u".env('DB_USERNAME', 'root').$pass_if_pass.
            env('DB_DATABASE', 'db')." < database/seeds/sitestrings_seed.sql");
    }
}

Why root, unless specified in .env another user? Thanks in advance for your reply

Upvotes: 3

Views: 3049

Answers (2)

Nelson Katale
Nelson Katale

Reputation: 1539

Always reference your .env variables only from the config files. To do this go to your config file app.php and add your .env variables defined in the .env file inside the return array like this

return [
    'db_username' => env('DB_USERNAME'),
    'db_password' => env('DB_PASSWORD'),
    'database' => env('DB_DATABASE'),
];

In your application code use configuration helper config('app.db_username'); to get the value of the .env variable DB_USERNAME. By doing this the configuration caching will work correctly.

Upvotes: 2

jOshT
jOshT

Reputation: 1675

You should be able to use the Config facade:

Config::get('filename.attribute');

For example:

Config::get('app.name);

Upvotes: 0

Related Questions