Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get environment value in controller

In my .env file I have the following:

IMAP_HOSTNAME_TEST=imap.gmail.com [email protected] IMAP_PASSWORD_TEST=mypw 

Now I would like to use them in my controller. I've tried this, but without any result:

$hostname = config('IMAP_HOSTNAME_TEST'); 

The $hostname variable is equal to null. How can I use these configuration variables in my controller?

like image 914
nielsv Avatar asked Dec 14 '15 09:12

nielsv


People also ask

How do I know my environment variable value?

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

How do I get data from .ENV in Python?

getenv() method is used to extract the value of the environment variable key if it exists. Otherwise, the default value will be returned. Note: The os module in Python provides an interface to interact with the operating system.


2 Answers

Try it with:

<?php $hostname = env("IMAP_HOSTNAME_TEST", "somedefaultvalue"); ?> 
like image 145
Chetan Ameta Avatar answered Sep 23 '22 07:09

Chetan Ameta


It Doesn't work in Laravel 5.3+ if you want to try to access the value from the controller like below. It always returns null

<?php      $value = env('MY_VALUE', 'default_value'); 

SOLUTION: Rather, you need to create a file in the configuration folder, say values.php and then write the code like below

File values.php

<?php      return [          'myvalue' => env('MY_VALUE',null),          // Add other values as you wish 

Then access the value in your controller with the following code

<?php      $value = \Config::get('values.myvalue') 

Where "values" is the filename followed by the key "myvalue".

like image 41
Masum Ahmed Sarkar Avatar answered Sep 22 '22 07:09

Masum Ahmed Sarkar