Sling Academy
Home/PHP/How to use environment variables in Laravel

How to use environment variables in Laravel

Last updated: January 18, 2024

Introduction

Environment variables in Laravel are crucial for setting up application configurations that are environment-specific. They allow you to manage settings for your application’s execution context such as local, staging, and production without changing your code base. This tutorial will guide you through the process of using environment variables in a Laravel application, providing multiple code examples along the way.

Understanding .env Files

Laravel utilizes the .env file to manage environment-specific configurations. It is located at the root of your Laravel project. This file is not committed to your version control system, as it can contain sensitive information such as API keys, database credentials, and more.

Each line in .env file sets a variable in the KEY=VALUE format. Example:

APP_NAME=Laravel
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Accessing Environment Variables

You can access environment variables using the global env() function. For example, to get the application name, you can use:

$appName = env('APP_NAME', 'defaultAppName');

Using Configuration Files

Laravel’s configuration files are located in the config directory. You can access the environment variables within these files using the env() function:

'debug' => env('APP_DEBUG', false),

This allows the application to fetch the correct configuration value for the current environment.

Caching Configuration

When you run php artisan config:cache, Laravel creates a configuration cache for better performance. Remember that, once the configuration is cached, the .env file won’t be used. Thus, you should only cache your configuration for production.

Using Environment Variables for Services

Often, you’ll need to customize the configuration of third-party services such as mail drivers, API connections, etc. You can set these configurations in their respective files within the config/services.php file and reference environment variables:

'stripe' => [
    'model' => App\Models\User::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

Setting Up Environment-Based Config

You can use environment variables to define different configuration settings for different environments. For instance, you may use a local database during development and a different one in production:

'connections' => [
    'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        // ...
    ],
],

Best Practices

It’s important to follow best practices while using environment variables:

  • Do not store .env files in version control.
  • Sensitive keys should be kept out of the code base and only provided as environment variables.
  • Use different .env files for different environments.

Security Considerations

Storing sensitive configuration in the environment keeps them out of the code base, reducing the likelihood of exposing secrets with source code. However, it’s important to ensure these variables are kept secure, especially on shared hosting environments.

Conclusion

Using environment variables is an efficient way to make your Laravel application flexible and secure across different environments. Leveraging the utility of .env files and the env() function can streamline your development and deployment processes. This guide has given you the knowledge to effectively manage your configurations and use environment variables in your Laravel applications.

Remember to check the Laravel documentation for the latest on environment configuration and other best practices to keep your application secure and efficient.

Next Article: 3 Ways to Run Laravel on a Custom Port

Previous Article: How to run Laravel in a subdirectory of a domain

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array