.env
files are environment-specific files, used to house variables specific to the environment you're running in. You keep them out of version control.
Let's take a look at Laravel's default .env
file:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="Laravel"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
In a typical application this will grow over time, with more and more variables being added all the time.
In an example application that integrates with a service like Shopify, you'll likely need to maintain an absolute URL that differs for each environment (local, dev,staging, QA, production, etc).
We, of course, want to implement DRY (Don't Repeat Yourself), so repeating the domain name lots of times in the same file isn't an option - it will lead to human error when duplicating environments, and it's just not a good use of time.
Using variables inside .env
files
We can resolve this issue by using variables in .env
files.
The magic for this is to wrap the URL in curly braces and prefix with a $
symbol.
Let's have a look at the Shopify example above.
Set an APP_URL
:
APP_URL=https://example.com
Now reference that later on:
SHOPIFY_WEBHOOKS="${APP_URL}/shopify/webhook"
This would resolve to:
SHOPIFY_WEBHOOKS="https://example.com/shopify/webhook"
In Laravel APP_URL
is a common variable you will reuse, but APP_NAME
is also likely to be used a lot, especially for things like MAIL_FROM_NAME
and such. It's useful to use variables wherever possible, even for things that like an APP_NAME
which you may think will never change, but you might wish to change this to something specific per environment, such as:
APP_NAME="My App (Staging - staging.example.com)"
This way you're able to identify things like email coming from staging or QA environments easily.
Top comments (0)