2

In laravel I need to create variable in env file. According to documentation and some relevant threads (got after googling) I need to do add variables in .env file

I have tried following

SANDBOX_PAYPAL_CLIENT_ID=7I3D9
SANDBOX_PAYPAL_CLIENT_SECRET=S2E4C5R6E7T

I am confused that after adding here variable I just need to call then into controller or I need to setup again in somewhere ./config/ directory? What is best practice, can someone guide me about that. I would like to appreciate. Thank you

Madhuri Patel
  • 1,270
  • 12
  • 24
Imran Abbas
  • 755
  • 1
  • 7
  • 24
  • https://laravel.com/docs/5.8/configuration#retrieving-environment-configuration – Andrei Lupuleasa Apr 18 '19 at 06:58
  • Possible duplicate of [Laravel Environment Variables 5.3 setup](https://stackoverflow.com/questions/39966347/laravel-environment-variables-5-3-setup) – Andrei Lupuleasa Apr 18 '19 at 07:02
  • Possible duplicate of [How to change variables in the .env file dynamically in Laravel?](https://stackoverflow.com/questions/32307426/how-to-change-variables-in-the-env-file-dynamically-in-laravel) – Madhuri Patel Apr 18 '19 at 07:07

3 Answers3

2

You should put env variables in .env file, but make sure to only use env() calls in configuration files (the ones under /config) to retrieve their values.

Keep in mind that if you cache the configuration (php artisan config:cache) any env() will return null as Laravel will no longer load .env files.

That's also stated in to the documentation

mdexp
  • 3,492
  • 2
  • 9
  • 20
1

You can get .env variables using the env() helper function. Most packages get these values in their conf file to group the configurations. You can then use the config() helper function to get the value.

However you implement this is up to you.

Mike
  • 852
  • 9
  • 17
-1

It depends on how you want to use them. Maybe create a file with name ConfigVariables.php declare all variables of env there.

1) You can have all of them at one place. Centralized control of all env variables at one place.

2) Take care of null checks etc, if config doesn't exit, pass some default value

3) This will help you to have one standard being used for all

4) If you use env directly in the code, you will have to check and take care of the null values (in case if there is no variable in the config)

Just to add a point here, Strings with spaces could be an issue if you do not use ""

You can test it:

Email_Sender_Name=Danyal Sandeelo
echo it as: echo env("Email_Sender_Name");

Email_Sender_Name="Danyal Sandeelo"
echo it as: echo env("Email_Sender_Name");

You can read this one: Laravel 5.2 not reading env file

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78