Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

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

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 = DotenvDotenv::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 = DotenvDotenv::createImmutable(base_path(), '.env.' . $host);
$dotenv->load();

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

question from:https://stackoverflow.com/questions/66060051/how-to-load-custom-env-file-in-laravel-console-command

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = DotenvDotenv::createMutable(base_path(), $env_name);
        try{
             $dotenv->load();
             $this->info(env('NAME'));
             $this->info('The Dotenv was loaded successfully!');
        } catch(DotenvExceptionInvalidPathException $e){
             $this->error($e->getTraceAsString());
        }
    }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...