Encrypting environment variables in Laravel can be done using the encrypt and decrypt functions provided by Laravel's Illuminate\Support\Facades\Crypt facade. Here's a simple flow to encrypt an environment variable for staging:
- Generate an encryption key for your staging environment by running the following command in your terminal:
php artisan key:generate --env=staging
This will generate a new key and store it in your .env.staging file.
- Set the
LARAVEL_ENV_ENCRYPTION_KEYenvironment variable to the encryption key you just generated. You can do this by adding the following line to your.env.stagingfile:
LARAVEL_ENV_ENCRYPTION_KEY=your-encryption-key-here
- Encrypt the environment variable you want to protect using the
encryptfunction. For example, if you want to encrypt theDB_PASSWORDvariable, you can do the following in yourconfig/database.phpfile:
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => encrypt(env('DB_PASSWORD')),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
],
- When you deploy your application, you'll need to decrypt the encrypted environment variables. You can do this by adding the following line to your deployment script:
php artisan env:decrypt --env=staging
This will decrypt all the encrypted environment variables in your .env.staging file.
- Finally, you can commit the encrypted
.env.stagingfile to your repository. However, make sure to add it to your.gitignorefile so that it doesn't get committed accidentally.
Note: It's important to keep your encryption key secret. Make sure to store it securely and don't share it with anyone.