Weave 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

avris/dotenv

Tiny PHP dotenv loader for reading .env files and injecting variables into the environment, $_ENV, and $_SERVER. Supports common KEY=VALUE syntax, quotes, comments, and safe defaults to keep config out of code and VCS.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require avris/dotenv
    
  2. Basic Setup Load .env files in your bootstrap/app.php (or equivalent entry point):

    use Avris\Dotenv\Dotenv;
    
    $dotenv = Dotenv::createImmutable(__DIR__.'/../');
    $dotenv->load();
    
  3. First Use Case Access environment variables via Laravel’s env() helper or directly:

    $apiKey = env('API_KEY'); // Standard Laravel way
    $apiKey = Dotenv::get('API_KEY'); // Direct package access
    

Implementation Patterns

Core Workflows

  1. Standard .env Handling Replace or supplement Laravel’s default .env loading:

    // In bootstrap/app.php
    $dotenv = Dotenv::createImmutable(__DIR__.'/../');
    $dotenv->load(); // Loads .env file
    
  2. Custom File Paths Load .env files from non-standard locations (e.g., per-environment):

    $dotenv = Dotenv::createImmutable(__DIR__.'/../../config/envs');
    $dotenv->load('staging.env'); // Loads ./config/envs/staging.env
    
  3. Validation Enforce required variables and types:

    $dotenv = Dotenv::createImmutable(__DIR__.'/../');
    $dotenv->validate([
        'APP_ENV' => 'required|in:local,staging,production',
        'DB_PASSWORD' => 'required|string',
        'DEBUG_MODE' => 'boolean',
    ]);
    
  4. Runtime Overrides Dynamically update variables (e.g., for feature flags):

    $dotenv = Dotenv::createImmutable(__DIR__.'/../');
    $dotenv->overwrite(['FEATURE_NEW_DASHBOARD' => 'true']);
    

Laravel-Specific Patterns

  1. Service Provider Integration Bind the Dotenv instance to Laravel’s container:

    // In AppServiceProvider
    public function register() {
        $this->app->singleton(Dotenv::class, function () {
            return Dotenv::createImmutable(base_path());
        });
    }
    

    Then inject it into classes:

    use Avris\Dotenv\Dotenv;
    
    public function __construct(private Dotenv $dotenv) {}
    
  2. Artisan Commands Use the package to manage .env files via CLI:

    use Avris\Dotenv\Dotenv;
    use Illuminate\Console\Command;
    
    class EnvCommand extends Command {
        protected $signature = 'env:load {path}';
        public function handle() {
            $dotenv = new Dotenv();
            $dotenv->load($this->argument('path'));
            $this->info('Environment loaded!');
        }
    }
    
  3. Configuration Caching Cache parsed .env files alongside Laravel’s config:

    $dotenv = Dotenv::createImmutable(base_path());
    $cached = $dotenv->loadIfExists(); // Loads if .env exists and is cached
    

Gotchas and Tips

Pitfalls

  1. Double Loading

    • Issue: Loading .env twice (e.g., in bootstrap/app.php and a service provider) can overwrite values.
    • Fix: Use Dotenv::createImmutable() to prevent reloading:
      $dotenv = Dotenv::createImmutable(base_path());
      $dotenv->loadIfExists(); // Only loads if not already loaded
      
  2. Validation Errors

    • Issue: Strict validation can break deployments if .env files are missing required keys.
    • Fix: Use safeLoad() or loadIfExists() to avoid crashes:
      $dotenv->safeLoad(); // Returns false if file is missing/malformed
      
  3. Laravel Conflicts

    • Issue: Mixing env() and Dotenv::get() can lead to inconsistencies if values are set in both.
    • Fix: Standardize on one approach (e.g., prefer Dotenv for custom logic).
  4. Performance Overhead

    • Issue: Frequent runtime reloads (e.g., in middleware) can slow down requests.
    • Fix: Cache parsed environments:
      $dotenv = Dotenv::createImmutable(base_path());
      $dotenv->load(); // Load once at boot
      

Debugging Tips

  1. Inspect Loaded Variables Dump all loaded variables for debugging:

    $dotenv = Dotenv::createImmutable(base_path());
    $dotenv->load();
    dd($dotenv->getAll()); // Shows all parsed key-value pairs
    
  2. Check File Paths Verify the correct .env file is being loaded:

    $dotenv = Dotenv::createImmutable('/custom/path');
    $dotenv->load('custom.env');
    
  3. Validation Errors Get detailed validation feedback:

    $dotenv = Dotenv::createImmutable(base_path());
    $errors = $dotenv->validate([
        'DB_HOST' => 'required|string',
    ]);
    if ($errors) {
        dd($errors); // Shows validation failures
    }
    

Extension Points

  1. Custom Parsers Extend the package to support non-standard .env formats:

    $dotenv = new Dotenv();
    $dotenv->setParser(function ($content) {
        // Custom parsing logic
        return parse_custom_env($content);
    });
    
  2. Event Listeners Trigger actions when .env files are loaded:

    $dotenv = new Dotenv();
    $dotenv->onLoad(function () {
        Log::info('Environment loaded');
    });
    
  3. Integration with Laravel Events Listen to Laravel’s boot events to load .env dynamically:

    use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;
    
    // Override Laravel’s default env loading
    LoadEnvironmentVariables::macro('custom', function () {
        $dotenv = new Dotenv();
        $dotenv->load(base_path('.env.custom'));
    });
    

Configuration Quirks

  1. Case Sensitivity

    • The package respects .env case sensitivity (e.g., DB_HOST ≠ db_host).
  2. Empty Values

    • Empty values (KEY=) are treated as empty strings, not null.
  3. Boolean Parsing

    • Uses PHP’s native casting (e.g., true/false, 1/0, yes/no).
  4. Array Support

    • Supports multi-line values (e.g., ALLOWED_IPS=192.168.1.1\n10.0.0.1).

Best Practices

  1. Use .env.example Document required variables in .env.example:

    # .env.example
    APP_ENV=local
    DB_DATABASE=homestead
    
  2. Avoid Hardcoding Fallbacks

    • Prefer Dotenv::safeLoad() over Laravel’s env() fallbacks to fail fast.
  3. Environment-Specific Files Use naming conventions for clarity:

    .env                # Default
    .env.local          # Local overrides
    .env.staging        # Staging-specific
    
  4. CI/CD Integration Validate .env files in pipelines:

    # GitLab CI example
    test:
      script:
        - composer require avris/dotenv
        - php -r "require 'vendor/autoload.php'; (new \Avris\Dotenv\Dotenv())->validate(['APP_ENV' => 'required']);"
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast