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

mykehowells/dotenv

Load and manage environment variables in PHP/Laravel using .env files. Simple API for reading config values across local, staging, and production setups, making it easy to keep secrets and per-environment settings out of code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require mykehowells/dotenv
    

    Add to composer.json under autoload:

    {
        "autoload": {
            "files": [
                "vendor/mykemeynell/dotenv/dotenv.php"
            ]
        }
    }
    

    Run composer dump-autoload.

  2. Basic Usage: Place a .env file in your project root (e.g., APP_NAME=MyApp). Load it in your bootstrap file (e.g., public/index.php or bootstrap/app.php):

    require __DIR__.'/vendor/mykemeynell/dotenv/dotenv.php';
    $dotenv = new Dotenv\Dotenv(__DIR__);
    $dotenv->load();
    
  3. First Use Case: Access environment variables like Laravel:

    $appName = env('APP_NAME', 'DefaultApp'); // Returns 'MyApp' or fallback
    

Implementation Patterns

Workflows

  1. Standard Laravel Integration: Replace env() calls in non-Laravel projects with this package’s env() function. Mimics Laravel’s behavior:

    $dbHost = env('DB_HOST', 'localhost');
    
  2. Configuration Files: Use .env for environment-specific settings (e.g., DB_PASSWORD=secret123 in .env.dev). Override defaults dynamically:

    if (app()->environment('local')) {
        $dotenv->load(__DIR__.'/../.env.local');
    }
    
  3. Validation: Validate .env values early (e.g., in a bootstrap/validate-env.php):

    $requiredVars = ['APP_KEY', 'DB_HOST'];
    foreach ($requiredVars as $var) {
        if (empty(env($var))) {
            throw new RuntimeException("Missing required env var: {$var}");
        }
    }
    
  4. Testing: Load test-specific .env files:

    $dotenv->load(__DIR__.'/../../.env.testing');
    

Integration Tips

  • Service Providers: Register the package in a service provider’s boot() method for global access.
  • Caching: Cache parsed .env values in production to avoid repeated file reads:
    if (!app()->bound('env-cache')) {
        app()->singleton('env-cache', function () {
            return $dotenv->parse();
        });
    }
    
  • Fallbacks: Use nested fallbacks for multi-environment setups:
    $value = env('APP_DEBUG', env('DEBUG_MODE', false));
    

Gotchas and Tips

Pitfalls

  1. File Paths:

    • The package expects .env in the root directory by default. Explicitly specify paths:
      $dotenv = new Dotenv\Dotenv(__DIR__.'/../config');
      
    • Relative paths may break in CLI vs. web contexts.
  2. Caching Issues:

    • Changes to .env won’t reflect until the script restarts. Clear opcache or restart PHP-FPM:
      php -r "opcache_reset();"
      
  3. Variable Overrides:

    • Later load() calls overwrite previous values. Use separate files for environments:
      $dotenv->load(__DIR__.'/../.env.base');
      $dotenv->load(__DIR__.'/../.env.local'); // Overrides base
      
  4. Security:

    • Never commit .env to version control (add to .gitignore).
    • Use php artisan env:encrypt (if paired with Laravel) or manually encrypt sensitive values.

Debugging

  • Missing Variables: Check for typos in .env keys or file paths. Use:
    var_dump(env()); // List all loaded variables
    
  • Syntax Errors: .env files must use KEY=VALUE format. Validate with:
    php -r "if (!file_exists('.env')) die('Missing .env file\n');"
    

Extension Points

  1. Custom Parsers: Extend Dotenv\Dotenv to support non-standard formats (e.g., YAML):

    class CustomDotenv extends Dotenv\Dotenv {
        public function parse() {
            $data = yaml_parse_file($this->filePath);
            return array_merge(parent::parse(), $data);
        }
    }
    
  2. Event Hooks: Trigger events on .env load (e.g., log changes):

    $dotenv->onLoad(function () {
        logger()->info('Environment loaded:', ['vars' => env()]);
    });
    
  3. Dynamic Paths: Use runtime logic to determine .env paths:

    $envPath = getenv('ENV_PATH') ?: __DIR__.'/../.env';
    $dotenv->load($envPath);
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity