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

Laravel Env Switcher Laravel Package

vizrex/laravel-env-switcher

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require vizrex/laravel-env-switcher
    

    Publish the package config (if needed):

    php artisan vendor:publish --provider="Vizrex\EnvSwitcher\EnvSwitcherServiceProvider"
    
  2. First Use Case: Switch to the dev environment:

    php artisan env:switch dev
    

    Verify the .env file reflects the dev configuration, and check for .env.dev.active (the previous active file).


Where to Look First

  • Command Signature: php artisan env:switch {new_env} [--force]
    • {new_env}: dev, prod, or testing.
    • --force: Override safety checks (e.g., uncommitted changes).
  • File Structure: The package manages:
    • .env (active environment)
    • .env.{env}.active (previously active environment)
    • .env.{env} (environment-specific configs, auto-created from .env.example if missing).

Implementation Patterns

Workflows

  1. Local Development:

    • Switch between dev and testing frequently:
      php artisan env:switch dev   # For feature development
      php artisan env:switch testing # For test runs
      
    • Use --force to bypass warnings (e.g., during CI/CD):
      php artisan env:switch prod --force
      
  2. Environment-Specific Configs:

    • Store sensitive keys (e.g., DB_PASSWORD) in .env.dev/.env.prod.
    • Override non-sensitive values (e.g., APP_DEBUG=true) per environment.
  3. CI/CD Integration:

    • Automate environment switching in deployment scripts:
      # Example: Deploy to staging
      php artisan env:switch testing
      php artisan migrate --env=testing
      
  4. Backup/Restore:

    • Backup: Copy .env to .env.backup manually before switching.
    • Restore: Use env:switch to revert, then manually restore .env.backup if needed.

Integration Tips

  1. Git Ignore: Add these to .gitignore to avoid committing environment files:

    .env
    .env*.active
    .env.dev
    .env.prod
    .env.testing
    
  2. Custom Environments: Extend the package by modifying the EnvSwitcherServiceProvider:

    • Add new environments in config/env-switcher.php:
      'environments' => [
          'dev', 'prod', 'testing', 'staging'
      ],
      
    • Update the switchEnv() logic in EnvSwitcherCommand.php to handle new files.
  3. Pre-Switch Hooks: Add validation before switching (e.g., check for uncommitted changes):

    // In EnvSwitcherCommand.php
    protected function prepareSwitch()
    {
        if (!app()->environment('local') && !$this->option('force')) {
            $this->error('Switching environments is disabled in non-local environments. Use --force to override.');
            exit(1);
        }
    }
    
  4. Post-Switch Actions: Chain commands after switching (e.g., restart queues):

    php artisan env:switch prod && php artisan queue:restart
    

Gotchas and Tips

Pitfalls

  1. File Permissions:

    • Ensure the Laravel storage directory and .env files are writable:
      chmod -R 775 storage bootstrap/cache
      
    • Fix permission errors with:
      sudo chown -R $USER:$USER .
      
  2. Missing .env.example:

    • If .env.example is missing, the package will fail to create new environment files.
    • Fix: Copy .env to .env.example or create it manually:
      cp .env .env.example
      
  3. Active File Conflicts:

    • If .env.{env}.active exists but .env is missing, the package may behave unpredictably.
    • Fix: Manually restore .env from backup or recreate it:
      cp .env.example .env
      
  4. Caching Issues:

    • After switching environments, clear Laravel caches:
      php artisan config:clear
      php artisan cache:clear
      

Debugging

  1. Dry Run: Test the switch without modifying files by inspecting the package’s logic in EnvSwitcherCommand.php:

    // Temporarily add logging:
    protected function copyEnvFile($source, $destination)
    {
        $this->info("Copying: {$source} -> {$destination}");
        file_put_contents($destination, file_get_contents($source));
    }
    
  2. Check File States: Use ls -la to verify file states:

    ls -la .env*  # Look for `.active` files or missing configs
    
  3. Environment Detection: Debug current environment with:

    php artisan env
    

    Or check Laravel’s environment:

    // In a Tinker session:
    app()->environment();
    

Tips

  1. Alias the Command: Add an alias to ~/.bashrc or ~/.zshrc for faster access:

    alias envswitch='php artisan env:switch'
    

    Then use:

    envswitch dev
    
  2. Environment-Specific .gitignore: Use a template to auto-generate .gitignore entries for all environments:

    echo ".env\n.env*.active\n.env.dev\n.env.prod\n.env.testing" > .gitignore
    
  3. Backup Strategy: Automate backups before switching:

    #!/bin/bash
    cp .env .env.backup-$(date +%Y%m%d)
    php artisan env:switch $1
    
  4. Custom Naming: Rename environment files to match your project’s conventions (e.g., .env.local):

    • Override the getEnvFilePath() method in EnvSwitcherCommand.php:
      protected function getEnvFilePath($env)
      {
          return base_path(".env.{$env}");
      }
      
  5. Force Flag Safety: Use --force sparingly. Instead, handle edge cases in the prepareSwitch() method:

    if (file_exists('.env') && md5_file('.env') !== md5_file('.env.example')) {
        $this->warn('Warning: .env has customizations. Use --force to proceed.');
    }
    
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.
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor