Laravel Framework: Environment Variables (env.) into Controller Class
2 min readFeb 14, 2020
After setting up your Laravel Project, you might want to add your custom environment variable.
- Create or Add Laravel Variable/s located at
.env
file
API_SECRET=FQD2duGaJwdryxEvSpt/OXFjkYvwIJz6vVBwEcxoIe0=
- On the terminal run
$ php artisan config:clear$ php artisan config:cache
If you execute the config:cache
command during your deployment process, you should be sure that you are only calling the .env function within your configuration files.
Once the configuration has been cached, the .env file will not be loaded and calls to the env function will return null.
- Go to your config folder and update
app.php
. - Add your config object
- Go to your terminal
- Create a Laravel class by running
php artisan make:controller BlogController
- On your created controller.
i.e BlogController.php add the following.
What happened here?
- We’ve used
Config
Laravel class - Created
public $API_SECRET
variable - Created
__constructor
and set$this->API_SECRET
to useConfig::get('app.api_secret.key').
- Created class function
getAPISecret()
to return$this->API_SECRET.
Result
FQD2duGaJwdryxEvSpt/OXFjkYvwIJz6vVBwEcxoIe0=
Thanks for reading and following along.
I hope that this blog will give value to you at some point. Please feel free to reach out if you have any questions.