Giedrius
Giedrius

Reputation: 1390

Laravel Artisan - reload .env variables or restart framework

I'm trying to write a command as a quickstart to build a project. The command asks for input for database details and then changes the .env file. The problem is that the command needs to do some Database queries afterwards, but the .env variables are not reloaded.

My question would be, is there a way to reload or override .env variables runtime. And if not, is there a way to call another Artisan command freshly, so framework bootstraps again?

In my command I tried doing $this->call('build:project') in my actual command, but even in the second call the variables are not reloaded.

Is there a way to achieve this without making the user manually call multiple commands?

Thanks!

Upvotes: 8

Views: 43865

Answers (4)

Kyobul
Kyobul

Reputation: 777

As OP I'm trying to bootstrap a Laravel project build by running console command and asking for the database credentials in the middle of the process.

This is a tricky problem and nothing I read was able to fix it : reset config, cache, Dotenv reload, etc... It seems that once the console command / operation is initialized the initial database connection is kept all over until the end.

The working solution I found is to bypass, after database modification are done, this cached state by using native shell exec command and passing the php artisan command as parameter :

passthru('php artisan migrate');

So, the order will be :

  1. php artisan project:build (or whatever is your console command)
  2. prompt the user for database credentials
  3. replace values in .env file (your search & replace algorythm)
  4. run php artisan config:cache
  5. passthru('php artisan migrate'); ro run your migrations

shell_exec would do the same but in silent mode while passthru will return the output generated by console. https://www.php.net/manual/en/function.passthru.php

Done successfully on Laravel 8.52

Upvotes: 0

Mladen Nikolic
Mladen Nikolic

Reputation: 31

Try to clear cache it helped me (couldn't ssh into the server)

Is there a {app route}/bootstrap/cache/config.php file on the production server? Delete it.

This helped me

Upvotes: 1

midodesign
midodesign

Reputation: 318

i had the same problem with reloaded .env variables, and i fixed it with this command line which allow you to clear the configuration :

php artisan config:clear

Hope that helped. Regards.

Upvotes: 14

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Laravel uses config files which take data from .env file. So, what you can do is to override configuration values at runtime:

config(['database.default' => 'mysql']);

Upvotes: 5

Related Questions