如何在 Laravel 控制台命令中加载自定义 .env 文件?

How to load custom .env file in Laravel console command?

我有这个控制台命令代码:

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;
    }
}

dd() 行中,它应该打印我作为参数给出的域(来自 .env.example.com,但仍然打印来自 .env 文件的数据。

否则此函数在 AppServiceProvider 中使用此代码运行良好:

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

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

知道如何让它在控制台命令中工作吗?

Immutability是指是否允许Dotenv覆盖已有的环境变量。
如果您希望 Dotenv 覆盖现有的环境变量,请改用 as Mu​​table

我是这样用的

   $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());
        }
    }