Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Dotenv Laravel Package

symfony/dotenv

Symfony Dotenv reads .env files and loads variables into PHP’s environment, exposing them via $_ENV and $_SERVER. Supports loading multiple files, overriding existing vars, and environment-specific .env.local/.env.$APP_ENV variants.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package (if not using Laravel’s built-in Dotenv):

    composer require symfony/dotenv
    

    Note: Laravel 10+ already bundles a Dotenv-compatible solution (vlucas/phpdotenv). Use this package only for non-Laravel contexts or Symfony integration.

  2. Basic Usage (e.g., in a CLI command or standalone script):

    use Symfony\Component\Dotenv\Dotenv;
    
    $dotenv = new Dotenv();
    $dotenv->load(__DIR__.'/../../.env'); // Load from project root
    

    Access variables via $_ENV['VAR_NAME'] or $_SERVER['VAR_NAME'].

  3. First Use Case:

    • Load environment-specific configs (e.g., .env.local, .env.prod) in a Symfony-based CLI tool or Lumen app:
      $dotenv->loadEnv(__DIR__.'/../../.env'); // Auto-loads .env.local, .env.prod, etc.
      

Implementation Patterns

1. Environment Hierarchy Management

  • Convention-based loading (replace Laravel’s manual .env files):
    $dotenv->loadEnv(__DIR__.'/../../.env'); // Loads:
    // .env
    // .env.local
    // .env.prod.local (if APP_ENV=prod)
    
  • Explicit file control (for custom paths):
    $dotenv->load(
        __DIR__.'/config/.env.db',
        __DIR__.'/config/.env.cache'
    );
    

2. Variable Overrides

  • Overwrite existing variables (useful for local overrides):
    $dotenv->overload(__DIR__.'/../../.env.local');
    
  • Deferred Expansion (resolve ${VAR} references after all files are loaded):
    # .env
    DB_HOST=localhost
    DB_PORT=${DB_PORT:-3306}  # Defaults to 3306 if DB_PORT is unset
    

3. Integration with Symfony Components

  • Use with Symfony Console:
    use Symfony\Component\Console\Application;
    use Symfony\Component\Dotenv\Dotenv;
    
    $dotenv = new Dotenv();
    $dotenv->load(__DIR__.'/../.env');
    $app = new Application();
    $app->run();
    
  • Access in Symfony Services:
    # config/services.yaml
    services:
        App\Service\ConfigService:
            arguments:
                $dbHost: '%env(DB_HOST)%'  # Resolved via $_ENV
    

4. Debugging Tools

  • Dump loaded variables (Symfony’s built-in command):
    php bin/console debug:dotenv
    
  • Validate .env files (check for BOM, syntax errors):
    try {
        $dotenv->load(__DIR__.'/invalid.env');
    } catch (\Symfony\Component\Dotenv\Exception\PathException $e) {
        // Handle invalid paths
    }
    

5. Laravel Workarounds

  • Bridge Laravel’s env() helper (if migrating to Symfony/Dotenv):
    function env(string $key, $default = null) {
        return $_ENV[$key] ?? $_SERVER[$key] ?? $default;
    }
    
  • Avoid conflicts with Laravel’s service provider:
    // In AppServiceProvider::boot()
    if (!app()->environment('local')) {
        $dotenv = new Dotenv();
        $dotenv->load(__DIR__.'/../../.env.prod');
    }
    

Gotchas and Tips

Pitfalls

  1. $_ENV vs. $_SERVER Precedence:

    • Symfony Dotenv populates both $_ENV and $_SERVER. In Laravel, $_SERVER takes precedence over $_ENV by default.
    • Fix: Use getenv() or $_ENV explicitly to avoid surprises:
      $value = getenv('VAR_NAME'); // Always checks $_ENV first
      
  2. Variable Expansion Order:

    • ${VAR} references are resolved after all files are loaded. Overriding a variable in a later file may break expansions:
      # .env
      APP_URL=http://${DOMAIN}
      DOMAIN=example.com
      
      Fix: Use overload() for critical overrides or restructure files.
  3. BOM (Byte Order Mark) Errors:

    • .env files with BOM (common in UTF-8 files from Windows) throw exceptions.
    • Fix: Re-save .env files as UTF-8 without BOM (use VS Code’s "Save with UTF-8" option).
  4. Laravel Caching Conflicts:

    • Laravel caches config after booting. Changing .env mid-request won’t reflect until cache is cleared.
    • Fix: Use php artisan config:clear or disable caching in config/caching.php.
  5. Self-Referencing Variables:

    • Circular references (e.g., A=${B} and B=${A}) cause infinite loops.
    • Fix: Use defaults or restructure:
      A=${B:-default_value}
      B=some_value
      

Debugging Tips

  • Inspect loaded variables:
    php -r "print_r($_ENV);"
    
  • Check file paths:
    $dotenv->setPath(__DIR__.'/custom/path'); // Override default path
    
  • Disable expansion (for testing):
    $dotenv->load(__DIR__.'/test.env', [], false); // 3rd arg: $override=false
    

Extension Points

  1. Custom File Paths:

    putenv('SYMFONY_DOTENV_PATH=/custom/env/path');
    $dotenv->loadEnv('/custom/env/path/.env');
    
  2. Subclassing for Validation:

    use Symfony\Component\Dotenv\Dotenv as BaseDotenv;
    
    class CustomDotenv extends BaseDotenv {
        protected function parse(string $content): array {
            $vars = parent::parse($content);
            // Add custom validation (e.g., regex checks)
            return $vars;
        }
    }
    
  3. Integration with Laravel’s bootstrap/app.php:

    $dotenv = new \Symfony\Component\Dotenv\Dotenv();
    $dotenv->load(__DIR__.'/../.env');
    

    Warning: Place this before Laravel’s Dotenv initialization to avoid conflicts.

Performance Notes

  • Avoid loading .env in production unless necessary (Symfony Dotenv is lightweight but still parses files).
  • Use overload() sparingly—it reprocesses all variables.

Laravel-Specific Quirks

  • APP_DEBUG Handling: Symfony Dotenv doesn’t set APP_DEBUG by default. Use:
    APP_DEBUG=true
    
    Or manually in bootstrap/app.php:
    define('APP_DEBUG', (bool) getenv('APP_DEBUG'));
    
  • Service Container Binding: Symfony Dotenv doesn’t auto-bind to Laravel’s container. Use:
    $this->app->bind('env', function () {
        return $_ENV;
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4