Introduction
Laravel utilizes the DotEnv PHP library by Vance Lucas. Env is a great tool to manage different configurations for different environment . We can use different configurations or different variables for environment that our app is running on (local, staging, production or any other).
For example : you may want to configure different cache driver locally and in production environment.
In a fresh laravel installation, you can find .env.example in the root directory . You can use below command to copy/create .env :
cp .env.example .env
.env file usually contains APP_NAME, APP_ENV, APP_KEY, database connection and many other . You can add your own variable and start using it.
Comment on .env file
We can comment our .env file using # character.
#ACCESS_KEY=YOUR_ACCESS_KEY #ACCCESS_TOKEN=YOUR_ACCESS_TOKEN #comment hello="value" #comment
Using Space in .env file
We can define a variable that contains spaces by enclosing the value with double quote.
HELLO="Hello Laravel Nepal"
Using Variables in .env file
Though env files seems small and manageable , why duplicate the same data right ?
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
In above line, PUSHER_APP_KEY and PUSHER_APP_CLUSTER is used in MIX_PUSHER_APP_KEY and MIX_PUSHER_APP_CLUSTER .
We can even do something like this :
BASE_DIR="/var/webroot/project-root"
CACHE_DIR="${BASE_DIR}/cache"
TMP_DIR="${BASE_DIR}/tmp"
Above example taken from github.
We’ve been going on and on about defining variables , now how do i retrieve the variable defined on env ?
It is quite easy . Let’s see a simple demonstration. We will define our own variable in env and get it .
// define HELLO in env Hello=Laravel-Nepal
To retrieve the env variable , we can use env() helper function.
env('HELLO');
We can even pass default value if the variable is not found as an second argument.
env('HELLO', 'Nepal');
All of the variables listed in this file will be loaded into the $_ENV PHP super-global when your application receives a request. ( Laravel )
We hope we were able to help you understand some deeper knowledge about env . If you have any queries or suggestions for us, feel free to contact us here.
Happy coding 🙂