All about .env encryption in Laravel 10

All about .env encryption in Laravel 10

Table of Content

In a Laravel project, it is not recommended and it is unsafe to send an unencrypted environment file to Git or any other source control. So, in this article, we will encrypt and decrypt the .env file and discuss everything in detail. If you want to know more, refer to the Laravel Official Documentation.

Encrypt and Decrypt simple .env file

Suppose we have a fresh Laravel project:

Laravel provides an easy way to encrypt a .env file using the artisan command.

php artisan env:encrypt // OR php artisan env:enc

Now we have encrypted our file and sent it for production.Now Suppose we don't have a .env file.If we try to decrypt it will ask us a key.

So it is very important to save that key , because we need it when we want to decrypt a file.If you have .env file then it will show. ERROR Environment file already exists. and if you don't have .env file, then it will create it.

Encrypting and Decrypting custom `.env.production` file

Suppose, you want to hide your main .env file and wanna use .env.production for production,then just copy .env and paste it and rename it .env.production

run the command
php artisan env:encrypt -h

Now if we want to encrypt .env.production then we need to specify the filename,using 3rd command from options.

php artisan env:encrypt --env=production
Now if you want to decrypt ,

You also have to tell the file name, if your exists,it will show you Environment File already exists and if you want to override the file just type --force in the artisan command.

Encrypting and Decrypting `.env` using our own key

You can also specify the key, instead of generating it automatically. If you want to use a custom key.

=Crypt::encryptString(‘your_String’)

It will generate a string, but we only need a 32-character key.

=substr(,0,32)

and then use that **same key** to decrypt the file.
Tags
Laravel Laravel 10 Laravel Env Env Encrypt Encryption Decryption Laravel Env Encryption Laravel Env Decryption Secure Env Env File Laravel .Env File Secure Laravel .Env Secure Secret Keys Laravel 10 Article Laravel Env Configuration .Env Configuration Env Advance