Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be using env() outside my config files?

Tags:

php

laravel

I stumbled across this https://laravel.com/docs/5.4/configuration#configuration-caching in the documentation and it confused me a bit.

When I want an environment variable I use the env() function to return what I want. According to the above link it says I should be using the config() function instead to ensure that on production I am accessing the values through a cache.

e.g. These both return the same thing

env('APP_URL')

vs

config('app.url')

So should I be using config() or env() inside my app?

I assume that if I add a new env variable I will also need to update my config files?

like image 401
Tom Headifen Avatar asked Dec 21 '17 17:12

Tom Headifen


People also ask

Is .env a config file?

In case you are still wondering what all this means, well, you are probably new to the . env file. It's actually a simple configuration text file that is used to define some variables you want to pass into your application's environment.

Should you use .env in Production?

Using environment variables is a somewhat common practice during Development but it is actually not a healthy practice to use with Production. While there are several reasons for this, one of the main reasons is that using environment variables can cause unexpected persistence of variable values.

Where should I put my .env file?

You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables.

Is .env necessary?

env files are simply too risky and cumbersome for modern application development. While . env files are still commonly used and were an improvement upon storing secrets in source code, the security risks and impact on developer productivity are only now being fully realized.


1 Answers

You should never use env() in the code directly. It's a good practice to use config(). In config files use env() to get the data from .env file.

In this case, you can easily override config values at runtime or during testing.

You also can use config caching.

To give your application a speed boost, you should cache all of your configuration files into a single file using the config:cache Artisan command.

Another reason is described in the docs:

You should typically run the php artisan config:cache command as part of your production deployment routine. If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files.

like image 78
Alexey Mezenin Avatar answered Oct 26 '22 04:10

Alexey Mezenin