【问题标题】:How to load custom .env file in Laravel console command?如何在 Laravel 控制台命令中加载自定义 .env 文件?
【发布时间】:2021-05-09 14:31:08
【问题描述】:

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

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

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

【问题讨论】:

  • 你试过$app->loadEnvironmentFrom('.env.example.com'); $app 你是 Laravel 应用吗。
  • 是的,也没有用

标签: laravel laravel-environment laravel-console


【解决方案1】:

不变性是指是否允许 Dotenv 覆盖现有的环境变量。
如果您希望 Dotenv 覆盖现有环境变量,请改用 as Mutable

这就是我使用它的方式。

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

【讨论】:

  • \Dotenv\Dotenv::createMutable 是解决方案!谢谢!
猜你喜欢
  • 2013-10-19
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 2021-05-11
  • 2017-08-08
相关资源
最近更新 更多