Get environment value in controller

PhpLaravelLaravel 5Config

Php Problem Overview


In my .env file I have the following:

IMAP_HOSTNAME_TEST=imap.gmail.com
IMAP_USERNAME_TEST[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?

Php Solutions


Solution 1 - Php

Try it with:

<?php $hostname = env("IMAP_HOSTNAME_TEST", "somedefaultvalue"); ?>

Solution 2 - Php

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".

Solution 3 - Php

To simplify: Only configuration files can access environment variables - and then pass them on.

Step 1.) Add your variable to your .env file, for example,

EXAMPLE_URL="http://google.com"

Step 2.) Create a new file inside of the config folder, with any name, for example,

config/example.php

Step 3.) Inside of this new file, I add an array being returned, containing that environment variable.

<?php
return [
  'url' => env('EXAMPLE_URL')
];

Step 4.) Because I named it "example", my configuration 'namespace' is now example. So now, in my controller I can access this variable with:

$url = \config('example.url');

Tip - if you add use Config; at the top of your controller, you don't need the backslash (which designates the root namespace). For example,

namespace App\Http\Controllers;
use Config; // Added this line

class ExampleController extends Controller
{
    public function url() {
        return config('example.url');
    }
}

Finally, commit the changes:

php artisan config:cache

--- IMPORTANT --- Remember to enter php artisan config:cache into the console once you have created your example.php file. Configuration 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.

Solution 4 - Php

All of the variables listed in .env file will be loaded into the $_ENV PHP super-global when your application receives a request. Check out the Laravel configuration page.

$_ENV['yourkeyhere'];

Solution 5 - Php

You can use with this format (tested on Laravel 5.5). In my case I used it for gettting the data of database connections and use on Controller:

$User = env('DB_USERNAMEchild','');
$Pass = env('DB_PASSWORDchild','');

The second parameter can be null, or set any default in case of DB_USERNAMEchild is null.

Your .env file can be the same:

DB_HOST=localhost
DB_DATABASE=FATHERBD
DB_USERNAME=root
DB_PASSWORD=password

DB_DATABASEchild=ZTEST
DB_USERNAMEchild=root
DB_PASSWORDchild=passwordofchild

Solution 6 - Php

It's a better idea to put your configuration variables in a configuration 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

config('mail.imap_hostname')

It first tries to get the configuration variable value in the .env file and if it couldn't find the variable value in the .env file, it will get the variable value from file config/mail.php.

Solution 7 - Php

In Controller

$hostname = $_ENV['IMAP_HOSTNAME_TEST']; (or) $hostname = env('IMAP_HOSTNAME_TEST');

In blade.view

{{$_ENV['IMAP_HOSTNAME_TEST']}}

Solution 8 - Php

As @Rajib pointed out, You can't access your env variables using config('myVariable')

  1. You have to add the variable to .env file first.
  2. Add the variable to some config file in config directory. I usually add to config/app.php
  3. Once done, will access them like Config::get('fileWhichContainsVariable.Variable'); using the Config Facade

Probably You will have to clear config cache using php artisan config:clear AND you will also have to restart server.

Solution 9 - Php

You can add the value into your .env file

 VALUE=somevalue
on the controller 
$_ENV['VALUE']
or
env('VALUE')

if it doesn't work, run this command

php artisan config:clear

Solution 10 - Php

You can not access the environment variable like this.

Inside the .env file you write

IMAP_HOSTNAME_TEST=imap.gmail.com  // I am okay with this

Next, inside the config folder there is a file, mail.php. You may use this file to code. As you are working with mail functionality. You might use another file as well.

return [

//..... other declarations
'imap_hostname_test' => env('IMAP_HOSTNAME_TEST'),
// You are hiding the value inside the configuration as well

];

You can call the variable from a controller using 'config(. Whatever file you are using inside config folder. You need to use that file name (without extension) + '.' + 'variable name' + ')'. In the current case you can call the variable as follows.

$hostname = config('mail.imap_hostname_test');

Since you declare the variable inside mail.php and the variable name is imap_hostname_test, you need to call it like this. If you declare this variable inside app.php then you should call

$hostname = config('app.imap_hostname_test');

Solution 11 - Php

In config/app.php file make a instance of env variable like 'name' => env('APP_NAME', 'Laravel') & In your controller call it like config('app.name')

Run following commands php artisan config:cache php artisan cache:clear if it is not working.

Solution 12 - Php

In the book of Matt Stauffer he suggest to create an array in your config/app.php to add the variable and then anywhere you reference to it with:

$myvariable = new Namearray(config('fileWhichContainsVariable.array.ConfigKeyVariable'))

Have try this solution? is good ?

Solution 13 - Php

Accepted answer not effective anymore after Laravel 5.2 version:

To get environment values in controllers or (any php file in laravel project) you have tow cases:

Case 1 (Predefined keys): If you need to get value from .env file which created by Laravel project as (default .env file), or by third party plugin you already installed it and follow the correct installation procedure of installation, See this answer for explain: https://stackoverflow.com/a/69707775/2877427

Case 2 (Not predefined keys - if you need generate new custom environment key): to do that follow these instructions:

  1. Add your custom key in .env file, for example i will add this key:

> UNIFONIC_APP_ID=xx2Erdasd7Ik7XfdesfaV9HX47 2. Add new php file in laravel_root/config folder, for example i will add this file config/custom.php and its contents like this:

return [



'unifonic_id' => env('UNIFONIC_APP_ID' , 'Here Default value will used of UNIFONIC_APP_ID not defined in .env file'),




];

];

  1. Run these tow commands in terminal:

> php artisan config:clear > php artisan config:cache

  1. Now in any php file (Controllers, Models, Views, ... etc) you can call this function:

> config('custom.unifonic_id');

Where custom is the name of php file which generated in step 2, and unifonic_id is the key of array which defined in step 2

This will return value if UNIFONIC_APP_ID which defined in .env, if not exists will return default value which defined in config file in step 2

> Note 1: config file can return multi dimensions array, take look for > structers of config files which located in laravel_root/config > folder.

> Note 2: you can modify file laravel_root/config/services.php insted > of create new config file...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnielsvView Question on Stackoverflow
Solution 1 - PhpChetan AmetaView Answer on Stackoverflow
Solution 2 - PhpMasum Ahmed SarkarView Answer on Stackoverflow
Solution 3 - PhpGrantView Answer on Stackoverflow
Solution 4 - PhpBasheer KharotiView Answer on Stackoverflow
Solution 5 - PhpZarkys SalasView Answer on Stackoverflow
Solution 6 - PhpHamid ParchamiView Answer on Stackoverflow
Solution 7 - PhpAnandan KView Answer on Stackoverflow
Solution 8 - PhpMacTavishView Answer on Stackoverflow
Solution 9 - PhpHabteSoftView Answer on Stackoverflow
Solution 10 - PhpRajibView Answer on Stackoverflow
Solution 11 - PhpYuvraj HingerView Answer on Stackoverflow
Solution 12 - PhpGencixView Answer on Stackoverflow
Solution 13 - PhpAnasSafiView Answer on Stackoverflow