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.
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 ?
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 :
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
To retrieve the env variable , we can use env() helper function.
We can even pass default value if the variable is not found as an second argument.
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 🙂