Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

Configuring Environment Variables with .env

Recommended resources

Hello! Welcome to the final lesson of our first module, "Laravel Foundations and Setup."

In our previous lesson, we explored the power of the Artisan CLI, learning how to serve our application, generate code, and manage tasks like clearing the cache with php artisan config:clear. That command hinted at a crucial concept: configuration. An application needs to know details like what database to connect to, what its name is, and whether it should show detailed errors. Storing this information directly in your code is inflexible and insecure.

This lesson focuses on Laravel's solution: the .env file. You will learn how to configure these "environment variables" to manage your application's settings securely and effectively for different environments, like your local machine versus a live server. This is a foundational skill for building any real-world application, especially the APIs you're aiming to create.

By the end of this lesson, you will be able to configure environment variables using the .env file, understand the security implications, and know the correct way to access these values throughout your application.


1. Environment Configuration: .env vs. .env.example

Every Laravel project comes with two key files in its root directory for handling configuration: .env and .env.example. Understanding their distinct roles is the first step.

  • .env.example: This is a template file. It lists all the environment variables your application needs to run. This file is committed to your version control (like Git). Its purpose is to show other developers (or your future self) what variables need to be set up.
  • .env: This is the actual configuration file that Laravel reads. It contains your specific, often secret, settings like database passwords and API keys. This file is unique to each environment (your computer, a staging server, a production server) and must never be committed to version control.

When you create a new Laravel project, the .env.example file is automatically copied to .env for you to fill out.

Laravel .env.example and .gitignore Files
An example of a `.env.example` file listing necessary variables, and a `.gitignore` file explicitly telling version control to ignore the actual `.env` file, protecting your secrets.

To grasp this fundamental concept, please watch the beginning of the following video.

Laravel .env.example: APP_XXX Values Explained

The video "Laravel .env.example: APP_XXX Values Explained" by Laravel Daily provides a concise explanation of the difference between the .env and .env.example files.

Watch from the beginning to 00:01:55. Focus on the distinction between the template file (.env.example) and the working file (.env), and why this separation is crucial for teamwork and security.

This separation is a core principle of modern web development. It allows you to keep your application's code (which is the same everywhere) separate from its configuration (which changes depending on where it's running).


2. Understanding Key Environment Variables

Now, let's open the .env file in your project and look at some of the default variables. While they might seem cryptic at first, they control essential aspects of your application.

APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

The following video explains the purpose of the most important APP_* variables.

Laravel .env.example: APP_XXX Values Explained

Let's continue with the Laravel Daily video, which breaks down what each of the main application variables does.

Watch from 00:01:55 to 00:09:36. Pay close attention to the explanations for: APP_ENV: How it determines the environment (local, production). APP_DEBUG: Its critical role in error display and security. APP_KEY: The application's encryption key. APP_URL: How it's used to build full URLs for links and assets.

Here's a quick summary of the most critical variables for now:

  • APP_ENV: Defines the current environment. This is typically local on your machine and production on a live server. You can use this to enable/disable features based on the environment.
  • APP_DEBUG: When true, Laravel displays detailed error pages. This is great for development but is a major security risk in production, as it can expose your code and server details. It should always be false in production.
  • APP_KEY: A unique, 32-character random string used for all encryption. If this is not set, your user sessions and other encrypted data will not be secure. You can generate one with the Artisan command: php artisan key:generate.
  • DB_* variables: These tell Laravel how to connect to your database. Your experience with SQL will make these familiar. We will use these settings extensively in the next module.

3. The Golden Rule: config() vs. env()

Now for the most important technical detail of this lesson. Laravel provides two helper functions to get configuration values: env() and config(). They are not interchangeable.

  1. The env('APP_NAME') function reads a value directly from your .env file.
  2. The config('app.name') function reads a value from a configuration file inside the config directory (in this case, config/app.php).

The configuration files in the config directory use the env() function to load values from .env. For example, config/app.php contains this line:

'name' => env('APP_NAME', 'Laravel'),

This reads the APP_NAME from .env and makes it available as app.name.

The Rule: You should only use the env() function inside the files in your config directory. Everywhere else in your application (controllers, models, etc.), you must use the config() function.

Why is this rule so strict? It's all about performance. In a production environment, you will run php artisan config:cache to combine all your config files into a single, quickly-loaded cached file. Once the configuration is cached, Laravel stops loading the .env file entirely. Any call to env() in your application code will return null, likely breaking your application. The config() function, however, will read from the fast, cached file and work perfectly.

The following video explains and demonstrates this critical concept.

Working with Laravel Config Files | Learn Laravel The Right Way

The video "Working with Laravel Config Files" by Program With Gio provides an excellent deep dive into the relationship between .env, config files, and caching.

Watch the segment from 00:12:34 to 00:18:47. This is the most crucial part of the lesson. Focus on understanding: What php artisan config:cache does. Why env('APP_NAME') returns null after caching. Why config('app.name') still works correctly.

Test your understanding!

You've added STRIPE_API_KEY=pk_live_... to your .env file for a payment service. In your PaymentController, you need to retrieve this key.

Which of the following is the correct and production-safe way to do this, and why?

A) Stripe::setApiKey(env('STRIPE_API_KEY'));
B) Create a file config/services.php with 'stripe' => ['secret' => env('STRIPE_API_KEY')], then use Stripe::setApiKey(config('services.stripe.secret')); in your controller.

Show answer

Option B is the correct way.

Using env() directly in a controller (Option A) is incorrect because it will fail when you run php artisan config:cache in production. By defining the key in a configuration file and accessing it with config() (Option B), your code will continue to work correctly whether the configuration is cached or not.



Conclusion

You have now mastered the fundamentals of configuration in Laravel. This knowledge is essential for building secure, flexible, and maintainable applications. By keeping configuration separate from code, you can easily deploy your application to different environments without changing a single line of your business logic.

Key Takeaways:

  • Separation of Concerns: The .env file holds environment-specific settings (like database passwords), while .env.example acts as a template for version control.
  • Security First: Your .env file should never be committed to a public repository. The APP_DEBUG variable must be set to false in production.
  • The Golden Rule: Use the env() helper only within your config directory files. Use the config() helper everywhere else in your application to ensure it works with Laravel's performance-boosting configuration cache.

Preview of the Next Module:
With this lesson, you have completed the "Laravel Foundations and Setup" module! You can now install Laravel, understand its structure, use Artisan for common tasks, and manage configuration.

In our next module, "Database and Eloquent ORM," we will put our database configuration to use. We'll begin by learning how to create and run database migrations using Artisan, allowing you to define and version-control your application's database schema directly from your code.