Skip to content

APP_KEY cant be set with key:generate when APP_KEY is already set in the environment#58340

Closed
nckrtl wants to merge 1 commit intolaravel:12.xfrom
nckrtl:12.x
Closed

APP_KEY cant be set with key:generate when APP_KEY is already set in the environment#58340
nckrtl wants to merge 1 commit intolaravel:12.xfrom
nckrtl:12.x

Conversation

@nckrtl
Copy link

@nckrtl nckrtl commented Jan 10, 2026

Consider this PR a bug report. I'm unsure yet what an elegant fix would be or if its intended behavior.

When running php artisan key:generate while APP_KEY has already been set in the environment the APP_KEY won't be set and a misleading error message "Unable to set application key. No APP_KEY variable was found in the .env file." will be shown.

You can also reproduce this on a mac or linux machine:

  1. Clone and set up a new vanilla Laravel application.
  2. Run export APP_KEY=abc on the command line.
  3. Run php artisan key:generate inside the application.
  4. Message "Unable to set application key. No APP_KEY variable was found in the .env file." will be shown.
  5. Clear the environment APP_KEY with unset APP_KEY on the command line, and the key:generate command will succeed.

This issue also occurs when generating Laravel apps through jobs with Horizon as the APP_KEY will be set in the environment when jobs are being processed.

If this is expected behavior then at least a proper error message should be shown. Especially for LLMs this would be helpful.

I provided a couple of tests where test_key_generate_updates_env_file_even_when_app_key_exists_in_environment demonstrates the the current behavior and fails.

This test file tests the key:generate command. The second test test_key_generate_updates_env_file_even_when_app_key_exists_in_environment demonstrates that APP_KEY won't be set when APP_KEY has already been set in the environment, which is unexpected.

Even if this is expected behaviour at least a proper error message should be shown. This is especially useful nowadays for LLMs to understand why key generation failed and come up with a workaround like using env -i (forcing empty environment)
@taylorotwell
Copy link
Member

PR to correct error message welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments