1

I have this console command code:

class MyCommand extends Command
{
    protected $signature = 'custom:mycommand {domain}';

    // ...

    public function handle()
    {
        $domain = $this->argument('domain');

        // read domain based .env file, like: .env.example.com
        $dotenv = \Dotenv\Dotenv::createImmutable(base_path(), '.env.' . $domain);
        $dotenv->load();

        dd(env('APP_URL'));

        // ...

        return 0;
    }
}

In the line of dd() it should print the domain what I gave as parameter (coming from .env.example.com, but still print the data from .env file.

Otherwise this function is working well in AppServiceProvider with this code:

$host = request()->getHost();

// read domain based .env file, like: .env.example.com
$dotenv = \Dotenv\Dotenv::createImmutable(base_path(), '.env.' . $host);
$dotenv->load();

Any idea how can I make it work in console command?

netdjw
  • 5,419
  • 21
  • 88
  • 162

1 Answers1

2

Immutability refers to if Dotenv is allowed to overwrite existing environment variables.
If you want Dotenv to overwrite existing environment variables, use as Mutable instead.

This is how I used it.

   $env_name = $this->argument('env_name');
   if(!empty($env_name) && is_string($env_name)){
        $dotenv = \Dotenv\Dotenv::createMutable(base_path(), $env_name);
        try{
             $dotenv->load();
             $this->info(env('NAME'));
             $this->info('The Dotenv was loaded successfully!');
        } catch(\Dotenv\Exception\InvalidPathException $e){
             $this->error($e->getTraceAsString());
        }
    }

bhucho
  • 3,903
  • 3
  • 16
  • 34