A better approach to keep Laravel .env files for multiple environments – Nivesh's blog
Published on

A better approach to keep Laravel .env files for multiple environments

Table of contents


Laravel comes with a .env file by default and it is called .env.example and we create a copy of .env.example file as .env

.env.example should not be in .gitignore as it is to be used as an example environment file for you and your team. You must add all new environment variables that you add in .env file to .env.example file as well so your team can be in sync with what variables are required for this project to run.

Now let's say if you need to make copy of .env.example for several environments i.e. development, staging, production the approach I use to name those files are as below:

  • .env.development.env
  • .env.staging.env
  • .env.production.env

One of the benefit of doing this is we get syntax highlighting in IDEs like PhpStorm or editors like Visual Studio Code.

How to add .env files to .gitignore

We should have all our custom .env files in .gitignore file at the root of our project so we don't accidentally push them to Github or any other platform via git. Here's an example of a basic .gitignore file:

## Laravel's default .gitignore


## Custom added files

*.env # It will cover all your custom env files with .env extension

A gentle reminder

Do not use env() helper in your project anywhere outside of config files. Using config() instead of env() is super important when you enable caching!

I've got more coming...

Want to hear from me when I add new post? Sign up for my newsletter and I'll email you every time I post a new article. (I'll never share your email and only send you updates about new articles.)