How to handle multiple env files in laravel?

Member

by aubrey , in category: PHP Frameworks , 2 months ago

How to handle multiple env files in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 2 months ago

@aubrey 

In Laravel, you can handle multiple environment files by creating separate files for each environment in the config directory.


Here are the steps to handle multiple environment files in Laravel:

  1. Create a new environment file: Duplicate the existing .env file in the root directory of your Laravel project and rename it to .env.example for the default configuration. Create a new file named .env.testing or .env.staging for your other environments.
  2. Update the configuration in the new environment file: Open the new environment file (e.g. .env.testing) and update the configuration settings for that environment. You can define environment-specific variables such as database settings, app settings, etc.
  3. Load the new environment file: In your config directory, create a new PHP file (e.g. testing.php or staging.php) to load the specific environment file. In this file, you can specify which environment file to load by using the Dotenv class:
1
2
3
4
5
6
7
8
$dotenv = DotenvDotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

if (getenv('APP_ENV') === 'staging') {
    $dotenv->load('.env.staging');
} elseif (getenv('APP_ENV') === 'testing') {
    $dotenv->load('.env.testing');
}


  1. Load the new configuration file in config/app.php: In the config/app.php file, update the env function to load the new configuration file:
1
'env' => env('APP_ENV', 'local'),


  1. Switch between environments: You can switch between environments by setting the APP_ENV variable in your environment file (e.g. APP_ENV=staging). When you run Laravel commands or access your application, it will load the corresponding environment file based on the APP_ENV value.


By following these steps, you can easily handle multiple environment files in Laravel and configure your application for different environments.