hansn
hansn

Reputation: 2024

Artisan unable to access environment variables from $_ENV

Any artisan command I enter into the command line throws this error:

$ php artisan
<?
return array(
    'DB_HOSTNAME'   => 'localhost',
    'DB_USERNAME'   => 'root',
    'DB_NAME'       => 'pc_booking',
    'DB_PASSWORD'   => 'secret',
);
PHP Warning:  Invalid argument supplied for foreach() in /home/martin/code/www/pc_backend/vendor/laravel/framework/src/Illuminate/Config/EnvironmentVariables.php on line 35
{"error":{"type":"ErrorException","message":"Undefined index: DB_HOSTNAME","file":"\/home\/martin\/code\/www\/pc_backend\/app\/config\/database.php","line":57}}

This is only on my local development system, where I recently installed apache and php. On my production system on a shared host artisan commands work just fine. The prod system has it's own .env.php, but other than that the code should be identical.

Relevant files:

.env.local.php

<?
return array(
    'DB_HOSTNAME'   => 'localhost',
    'DB_USERNAME'   => 'root',
    'DB_NAME'       => 'pc_booking',
    'DB_PASSWORD'   => 'secret',
);

app/config/database.php

<?php

return array(

'fetch' => PDO::FETCH_CLASS,

'default' => 'mysql',

'connections' => array(

    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => $_ENV['DB_HOSTNAME'],
        'database'  => $_ENV['DB_NAME'],
        'username'  => $_ENV['DB_USERNAME'],
        'password'  => $_ENV['DB_PASSWORD'],
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
),

'migrations' => 'migrations',

),

);

The $_ENV array is populated as expected on the website - the problem appears to be with artisan only.

Upvotes: 2

Views: 2431

Answers (1)

hansn
hansn

Reputation: 2024

So I finally figured out how to fix it. It turns out that the file was not processed as a php file because I was using a short opening tag in the .env.local.php file. Using a normal opening tag solved it. I don't know why though, as short tags work fine elsewhere.

Upvotes: 2

Related Questions