While troubleshooting HTTP 419 errors with someone in the Mastering Laravel Slack community, a question came up Laravel's application key, which is stored in .env
as APP_KEY
.
Is it possible that blowing away the composer.lock
file and running composer install
could change the application key?
Or is there anything else that could unexpectedly change the application key?
First, I searched the Laravel source for any references to APP_KEY
.
There is only one place where this value is written, and as you might expect, it's in the KeyGenerateCommand
console command.
So if we run php artisan key:generate
, it will change the value of APP_KEY
in the .env
file.
That's the whole point of that command, so no surprises there.
But if you take a look in the default composer.json
file for a Laravel project, you'll see that this command is called as part of the post-create-project-cmd
script too.
What does that mean?
If you run composer create-project laravel/laravel
(which was the default installation instruction in the docs prior to Laravel 11), it will run this script block.
That is quite helpful, since you need to set the application key before you can run your app.
What about the newer laravel installer, which you run with laravel new
?
Under the hood, it calls composer create-project
as well, so you get the same behavior.
But if you just delete your composer.lock
file, and re-run composer install
, that create-project
script will not run.
It only triggers when calling composer create-project
.
And you can't run create-project
against a non-empty folder, so you couldn't even accidentally trigger that script.
So after searching the source code, I can definitely say that your APP_KEY
will only be written when initially installing a new Laravel project, or if you run php artisan key:generate
manually.
Here to help,
Joel
P.S. Feel free to ask your Laravel question in the Mastering Laravel Slack community.