What could explain why env() randomly returns null, and changing it to config() seem to fix it? [duplicate] - laravel

This question already has answers here:
What is difference between use env('APP_ENV'), config('app.env') or App::environment() to get app environment?
(6 answers)
Closed 16 hours ago.
In some parts of the code I was using env() to read data from the .env file. It would randomly return null instead of the actual value and cause errors. (The values in question do not have quotes around them but they do not contain spaces, only special characters)
Then I came across this post: https://stackoverflow.com/a/42393294/18178584
So, I moved everything that was using env() to a config file, then replaced the code that was using env() with config() and looks like it solved the random null issue.
The post above does mention that it can cause problems in production. However, in my case, the issue happens in development environment as well, and I'm not sure anyone ran the caching commands
Is there a reason for that?

its not random, the env will return null when use anywhere outside the config file if there is a config cache present in bootstrap/cache/config.php
you can do some test
Route::get('test-envi', function() {
return [
'env' => env('APP_NAME'),
'config' => config('app.name')
];
});
without config cache (file dont exist bootstrap/cache/config.php), which you can delete running php artisan config:clear
the result would be
https://yoursite.com/test-envi
{
env: "YourAppName",
config: "YourAppName"
}
with config cache (file exist bootstrap/cache/config.php), which you add running php artisan config:cache or php artisan optimize
the result would be
https://yoursite.com/test-envi
{
env: null,
config: "YourAppName"
}
So; if you're getting null values calling env() function even if the key is present in .env file, that simply means your config was cached

Related

Laravel - Get current .env() Value

I am working on a Laravel project. I often change the database connection between Mysql and Sqlite during development. In a php artisan Laravel command I have an import routine. Because I don't want to write the data into the wrong database, I want to set an if condition before the import. But unfortunately it doesn't work quite as I imagined.
if ( env('DB_CONNECTION', null ) === 'sqlite') {
// Import to sqlite
} else if (env('DB_CONNECTION') === 'mysql') {
// Import to mysql
} else {
// no database in env DB_CONNECTION
}
In my .env file currrently the DB_CONNECTION is set on sqlite. But env('DB_CONNECTION', null) returns null.
What do I have to do to find out the current connection? Maybe using env() is not the right choice at this point?
For all those who will have the same problem in the future. Always! But really always, after you have modified the .env variable, you should execute the following "cleaning" commands:
php artisan config:cache
php artisan config:clear
If you still don't get a value, ask SO.
You should not use env() function anywhere except config files. Instead, use config('database.default'), because when configuration is cached, the env is empty for security reasons.
You may create multiple database connections in config/database.php and switch between them manually using facade: DB::connection('sqlite'), or DB::connection('mysql') and avoid this ugly if - else if tree.

Laravel Enviroment Variables are not working within Google Cloud Run

I've deployed too many times Laravel projects up to Cloud Run successfully, but right now
It looks like Cloud Run is unable to read Enviroment Variables (which i've specified already in the Variables&Secrets section within Cloud Run instance).
I'm using Laravel 8. For testing purposes (and make sure Cloud Run it's reading env variables), i've added a simple route in the api.php section like belows:
Route::get('/test-env', function () {
echo 'debuggeando<br>';
dd(config('variables.test_env'));
});
Into my config/variables.php i've the follows:
<?php
return [
'test_env' => env('TEST_ENV', 'no se encontro la variable')
];
And this is my final result:
What do am I doing wrong? Why Cloud Run is unable to read the enviroment variables from Laravel?
You can only make Laravel pick up envirnmental variables, but not the other way around.
config(['test_env' => getenv('TEST_ENV')]);
Running php artisan config:clear & php artisan config:cache might be required. Another option might be to generate a fresh .env file during the deployment, which merely translates to: already defining the value, before it can be cached.

Laravel after upgrade, .env variable Undefined index

I'm upgrading Laravel to 5.2 from 5.1. When i refere to variable API_DOMAIN in .env file using $_ENV
$_ENV['API_DOMAIN']
I get an error saying Undefined index: API_DOMAIN". Am I missing something here? should i do something after composer update?
Try using the env helper instead, env('API_DOMAIN')
Run the below commands after making changes in env file. It will flush and repopulate all the env variable.
php artisan config:cache //flush all cached env variable
php artisan config:clear //repopulate all the env variable
php artisan cache:clear //flush all the cached content
You should not directly work with environment values in your application, I would create a new configuration file or use an existing one and add the value there, this way you can cache the configuration.
Lets use your API_DOMAIN as an example:
.env file
API_DOMAIN=www.mydomain.com
Config file
config/api.php for example
<?php
return [
'domain' => env('API_DOMAIN'),
];
Now you can use the config helper to use this variable in your application:
$value = config('api.domain');
You should never use the env() helper outside of config files, because when you cache your config, env() will return null.

Laravel can't change config value

I found the problem, i'll try to use a homestead or docker.
if i restart php artisan serve the changed values are applied.
Same my post: Laravel can't change config value
I make route
Route::get('/config', function () {
return dd(config('app'));
});
And cant change my config/app.php, for example i want to change
'url' => env('APP_URL', 'test'),
'client_url' => env('APP_CLIENT_URL', 'test'),
I set
APP_CLIENT_URL=str1
APP_URL=str2
and there is something inexplicable:
My "url" => "http://127.0.0.1:8000" !!! not default 'test' or from .env, I did not set such a value.
My client_url contains the old value, after I cached the config.
This is not production, i accidentally run config:cache, but after i remove all cache from bootsrap/cache, storage/framework/cache and running cache:clear, config:clear.
After running config:cache values from the .env were put in config, but I do not want to constantly change cache in development and it is not recommended in the documentation.
How can I easily change .env in in developing?

What is difference between use env('APP_ENV'), config('app.env') or App::environment() to get app environment?

What is difference between use env('APP_ENV'), config('app.env') or App::environment() to get app environment?
I know that the env('APP_ENV') will to $_ENV, config('app.env') reads the configuration and App::environment() is an abstraction of all. And in my opinion the advantage is even this. Abstraction.
I do not know if there are other differences, such as the level of performance or security
In Short & up-to-date 2022:
use env() only in config files
use App::environment() for checking the environment (APP_ENV in .env).
use config('app.var') for all other env variables, ex: config('app.debug')
create own config files for your own ENV variables. Example:
In your .env:
MY_VALUE=foo
example config/myconfig.php
return [
'myvalue' => env('MY_VALUE', 'bar'), // 'bar' is default if MY_VALUE is missing in .env
];
Access in your code:
config('myconfig.myvalue') // will result in 'foo'
Explanation & History:
I just felt over it. When you cache your config file, env() will (sometimes?) not work right. So what I found out:
Laravel recommends only to use env() within the config files. Use the config() helper in your code instead of env(). For example you can call config('app.env') in your code.
When you use php artisan config:cache all the configuration strings are cached by the framework and any changes you make to your .env file will not be active until you run the php artisan config:cache command again.
From this article on Laracast:
UPDATE:
env() calls work as long as you don't use php artisan config:cache. So it's very dangerous because it will often work while development but will fail on production. See upgrade guide
Caching And Env
If you are using the config:cache command during deployment, you must
make sure that you are only calling the env function from within your
configuration files, and not from anywhere else in your application.
If you are calling env from within your application, it is strongly
recommended you add proper configuration values to your configuration
files and call env from that location instead, allowing you to convert
your env calls to config calls.
UPDATE Laravel 5.6:
Laravel now recommends in its documentation to use
$environment = App::environment();
// or check on an array of environments:
if (App::environment(['local', 'staging'])) {
// The environment is either local OR staging...
}
and describes that env() is just to retrieve values from .env in config files, like config('app.env') or config('app.debug').
You have two equally good options
if (\App::environment('production')) {...}
or
if (app()->environment('production')) {...}
app()->environment() is actually used by Bugsnag, look in documentation here it says
By default, we’ll automatically detect the app environment by calling the environment() function on Laravel’s application instance.
Now, differences:
1) env(...) function returns null after caching config. It happens on production a lot.
2) you can change config parameters inside unit tests, it gives you flexibility while testing.
One thing to consider is perhaps the convenience factor of passing string to app()->environment() in order validate your current environment.
// or App:: whichever you prefer.
if (app()->environment('local', 'staging')) {
logger("We are not live yet!");
Seeder::seedThemAll();
} else {
logger("We are LIVE!");
}
2023 Updated Answer
env() helper works when there is no config.php inside bootstrap/cache directory
config() helper works both in case if the file config.php is present or not. If the file is not present then if will parse the variables at runtime, but if it does find one; it uses the cached version instead.
In production environment the artisan commands we run to add/remove the config file.php becomes of paramount importance in context of how env() and config() behave.
Consider the following example to understand the concept:
Route::get('/', function () {
// to experiment: set APP_ENV=production in your .env file
echo 'Via env(): ' . env('APP_ENV') . '<br/>'; // production
echo 'Via config(): ' . config('app.env'); // production
/*
|--------------------------------------------------------------------------
| run: php artisan config:cache
|--------------------------------------------------------------------------
|
| The config:cache command will generate a configuration cache file (config.php) in the bootstrap/cache directory.
| At this point, the env() helper will no longer work as all ENV variables will be flushed in favor of the cached config.php file.
|
*/
echo '<hr/>';
echo 'Via env(): ' . env('APP_ENV') . '<br/>'; // null
echo 'Via config(): ' . config('app.env'); // production
/*
|--------------------------------------------------------------------------
| run: php artisan config:clear
|--------------------------------------------------------------------------
|
| The config:clear command will remove (config.php) configuration cache file from the bootstrap/cache directory.
| At this point, the env() helper will work again as framework doesn't find a cached configuration file.
|
*/
echo '<hr/>';
echo 'Via env(): ' . env('APP_ENV') . '<br/>'; // production
echo 'Via config(): ' . config('app.env'); // production
});
So general rule of thumb is to always use config() helper inside your code files; in this way your code does not explode if cached configuration file is available or not.
Now getting the environment is so important and common; Laravel gives us a handful ways we can accomplish the same:
// APP_ENV=production inside .env file
App::environment(); // production
app()->environment(); // production
App::environment('production'); // returns boolean: true
app()->environment('production'); // return boolean: true
Keep in mind you are using App facade or app() helper they all will be using config helper under the hood.
If you are using the config:cache command during deployment, you must make sure that you are only calling the env function from within your configuration files, and not from anywhere else in your application.
If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your env calls to config calls.
Add an env configuration option to your app.php configuration file that looks like the following:
'env' => env('APP_ENV', 'production'),
More: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0
In 12factor methodology application contains two types of configuration values:
internal which not vary between deploys and are stored in laravel ./config/ folder. In this type we usually store some technical optimal/good values used in application which should not be changed by users over time e.g. optimal image compression level, connection timeout, session expiration time etc.
external which vary between deploys and are stored in .env file (but should not be stored in git repo, however .env.example with example values with detail info can be stored in repo). In this type we store usually some important/protected values which depends on local environment e.g. passwords, debug mode, db address etc.
Laravel proposes handy approach for this
in regular code we use only config(...) helper (so on this level programmer do not need to know which configuration value is internal and which is external)
in configuration code external config values should be set using env(...) helper e.g. in config/app.php 'debug' => env('APP_DEBUG', false)

Resources