Tutorial

Understanding Laravel Environment Variables

Draft updated on Invalid Date
Default avatar

By Matthew Lenhard

Understanding Laravel Environment Variables

This tutorial is out of date and no longer maintained.

Introduction

With the introduction of Laravel 5 and the adoption PHPDotenv, Laravel environment variables have become easier to use than ever before. In today’s tutorial, I’ll walk you through how to get started using environment variables in your project.

Luckily the process is relatively simple for anyone familiar with other frameworks that utilize environment variables or anyone with a basic knowledge of Laravel.

Why You Should Use Environment Variables

Environment variables allow developers to extract sensitive credentials from their source code and use different configuration variables based on their working environment.

For most developers, their local machine has different database credentials than their production environment. While different database credentials are one of the most common differences between production and local environments there are a host of other configuration variables that may also differ.

Some environment variables that could differ are:

  • We want to use [Mailtrap](http://mailtrap.io/ to send test emails locally and use Mandrill to send real emails on our production server
  • We have different Facebook Developer Credentials for local vs production apps
  • We want to use file for Laravel sessions locally and redis for sessions on production

You will most likely also have a list of outside services your application connects to. Environment variables offer a way for you to extract these from your application and even vary them based on your environment.

Warning: We don’t want to keep security credentials in the git repo.

Environment variables can also be extremely helpful when creating and working on a testing environment. With relative ease, developers can switch between testing and production environments. Now that you understand some of the benefits of environment variables we can take look at how to implement them In your application.

Declaring Environment Variables in Your App

A successful Laravel install will include a .env example file in your application’s root folder.

If you installed Laravel with Composer then your .env.example file will have already been renamed to .env, if you did not install through composer then go ahead and rename your file.

If you are working in a team environment it may help to leave the .env.example file and use it as a way to show what environment variables are needed for the application to run.

Keep .env Out of Source Control

Your .env file should be kept out of your version control system. If you are using Git then add the .env file to the .gitignore file so that it will not be committed. Laravel handles this automatically for us in the default .gitignore file.

Your .env file should resemble something similar to this.

.env
    APP_ENV=local
    APP_DEBUG=true
    APP_KEY=SomeRandomString

    DB_HOST=localhost
    DB_DATABASE=homestead
    DB_USERNAME=homestead
    DB_PASSWORD=secret

    CACHE_DRIVER=file
    SESSION_DRIVER=file
    QUEUE_DRIVER=sync

Database Credentials

For this example, we will work through how to change your database configuration based on your environment. We will start by taking a look at config/database.php. This file holds the information necessary to connect to your database.

config/database.php
    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

Notice that most of the variables are set with the env() function. env() is one of the built-in helper functions in Laravel.

env() takes two parameters,

  1. Name of the environment variable in your .env file
  2. Default value if the environment variable cannot be found.

For example, if your config/databse.php MySql section and your .env file were to resemble the code snippets below your app would first look for DB_HOST in the .env file and since it was declared then set host in the mysql array equal to myHost.

config/database.php
    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],
.env
    DB_HOST=myHost
    DB_DATABASE=myDB
    DB_USERNAME=myUsername
    DB_PASSWORD=mySecret

If there was no DB_HOST environment variable then it would default to localhost. Since your .env file is not in your version control system you will need to create a .env file in your production environment.

Setting Production Environment Variables in Forge

When creating servers on Laravel Forge, there is an easy way to set these environment variables.

To set your environment variables in forge click on your server and then click manage next to your site’s name. Now click on the environment tab and you should see something similar to below.

Once you click edit environment, you’ll be able to see the full .env file that is stored on the server. Edit freely!

If you click edit environment you can now go ahead and add in your environment variables.

Other Servers

If you are running your server with amazon then the process is a little less user-friendly. You can start by using the SSH command to connect to your server and then running vim .env or sudo vim .env depending on your user privileges. Make sure to run this command at the root of your Laravel applications folder. By running vim .env you are creating a new file named .env and then opening it in the amazing Vim editor.

Vim is a text-based editor for Unix environments and is relatively simple to pick up with a little practice. If you are a novice you can add text with i and then when you are finished hit the escape button followed by :wq. the : informs vim you are running a command and wq tells Vim to save and quit.

Conclusion

Hopefully, you now have a much better understanding of environment variables in Laravel. Environment variables are essential tools for anyone looking to develop in an MVC framework across multiple environments.

Not only are you able to separate sensitive data from your application code, but you will also save time switching between local and production environments.

Feel free to reach out with any comments or questions below. Happy Coding!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Matthew Lenhard

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel