If you have some experience with Linux, you are probably quite familiar with environment variables. In Linux, you could check the available environment variables with the printenv command. A way to define environment variables in Linux would be to use the export command followed by the variable that you want to define, for example: export name=Orkhan.

In this tutorial, you will learn a couple of ways of defining Laravel variables and accessing them in your application!

Defining a variable in .env

The .env file holds your env variables for your current environment. It is powered by the DotEnv Library.

As the .env file often holds sensitive information like API keys or database credentials, you should never commit it to Git and never push it to GitHub.

In order to define a new environment variable, you could use the following syntax: VAR_NAME=YOUR_VALUE. For example, let's say that you wanted to define your GitHub API key in there, the syntax would be the following:

GITHUB_API_KEY=your_api_key_here

In case that you have spaces in the value, it is best to use quotes:

NAME="Orkhan Alishov"

Accessing the env variable with env()

Once you've specified your environment variable in your .env file, you could then retrieve it in your application with the following helper function:

env('NAME')

The env helper function allows you to pass a default value in case that the env variable is not defined or does not have a value specified in the .env file:

env('NAME', 'Taylor Otwell')

In the above example, if the NAME env variable is not defined, it will take the default value of Taylor Otwell.