In my .env file I have the following:
IMAP_HOSTNAME_TEST=imap.gmail.com
IMAP_USERNAME_TEST=myemail@gmail.com
IMAP_PASSWORD_TEST=mypw
Now I would like to use them in my controller. I've tried this but with no result:
$hostname = config('IMAP_HOSTNAME_TEST');
The $hostname variable is equal to null. How can I use these config variables in my controller?
It's a better idea to put your config variables in a config file.
In your case, I would suggest putting your variables in config/mail.php like
'imap_hostname' => env('IMAP_HOSTNAME_TEST', 'imap.gmail.com')
and refer to them by
It first tries to get config variable value in the .env file and if it couldn't find the variable value in the .env file it will get variable value from config/mail.php
Doesn't work in Laravel 5.3+ if you want to try to access the value from the controller like below, it returns always null
SOLUTION: Rather you need to create a file in config folder ..say values.php and then write the codes like below
values.php
Then access the value in your controller with the following code
Where "credentials" is the filename followed by the key "myvalue" Hope it helps
try it with
in Laravel Controlller
in Laravel Blade files
Example : Accessing Laravel .env variables in blade
Get environment value in controller
You can use with this format, (Tested on Laravel 5.5) in my case i used for get the data of database connections and use on Controller:
The second parameter can be null, or set any default in case of DB_USERNAMEchild is null.
you .env file can be the same:
I thought I'd add an answer, to simplify what has been said in the past. Only config files can access env variables - and then pass them on.
Step 1.) Add your variable to your
.env
file, ie.Step 2.) Create a new file inside of the
config
folder, any name, ie.Step 3.) Inside of this new file, I add an array being returned, containing that env variable.
Step 4.) Because I named it "example" my configuration 'namespace' is now example. So now, in my controller I can access this variable with:
Tip - if you add
use Config;
at the top of your controller, you don't need the backslash (which designates the root namespace). Ie.--- IMPORTANT --- Remember to enter into the console
php artisan config:cache
once you have created your example.php file. Config files and variables are cached, so if you make changes you need to flush that cache - the same applies to the.env
file being changed / added to.