108

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 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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nielsv
  • 6,540
  • 35
  • 111
  • 215
  • 1
    Possible duplicate of [Laravel 4: how can I get the environment value?](http://stackoverflow.com/questions/14935846/laravel-4-how-can-i-get-the-environment-value) – Narendrasingh Sisodia Dec 14 '15 at 09:16

14 Answers14

114

Try it with:

<?php $hostname = env("IMAP_HOSTNAME_TEST", "somedefaultvalue"); ?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
  • `somedefaultvalue` can be any default value in case `env` does not exists. – Chetan Ameta Dec 14 '15 at 09:34
  • 9
    Using `env()` can lead to unexpected issues, see Grant's answer on this question - https://stackoverflow.com/questions/34263107/get-environment-value-in-controller/54286878#54286878. – Steve Jan 30 '19 at 12:16
  • 3
    Doesn't work for Laravel 5.5. Please go down to find an answer by Masum Ahmed Sarkar – Hari Harker Jul 09 '19 at 08:13
  • Add a reducted form of this in the config/app.php file in Laravel 8^ and it will work. ```'hostname' = env('IMAP_HOSTNAME_TEST');``` – Steven Dec 08 '20 at 12:31
94

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

Community
  • 1
  • 1
  • 9
    Not sure why this was downvoted... It's the correct answer (mostly) for L5.3+. But using your example filename of `values.php`, you'd actually reference it in the controller as `$value = config('values.myvalue');` – Drew Hammond Mar 11 '18 at 21:00
  • 11
    Don't forget to `php artisan config:cache` to commit config changes. – Grant Apr 29 '18 at 13:27
88

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.

Grant
  • 5,709
  • 2
  • 38
  • 50
  • php artisan config:cache crash my aplication – Felipe Castillo May 31 '19 at 15:32
  • 1
    @FelipeCastillo means your application has an issue in its configuration - because that command only flushes the cache – Grant Jun 04 '19 at 10:31
  • 2
    config() is the helper function and does NOT need the `use Config;`. With the use statement you can use the alias `Config` for `Illuminate\Support\Facades\Config::class` like for example: `Config::get('example.url')` – Ametad Sep 22 '20 at 12:40
  • 1
    @petermortensen @Grant, this is a great answer. My question is why does this work as opposed to just using laravels ```env()``` helper method? – CodeConnoisseur Dec 02 '20 at 16:49
  • 1
    @PA-GW The env() helper accesses only the (often security sensitive) environment variables stored in the .env file. You'll notice in my opening line, I mentioned that it appears that (at least as of the date answering this question) configuration files are the only files that are able to access those sensitive super globals. – Grant Dec 03 '20 at 13:24
32

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'];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Basheer Kharoti
  • 4,202
  • 5
  • 24
  • 50
6

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zarkys Salas
  • 121
  • 1
  • 4
  • 1
    Where did you place this code, `config/app.php` or the controller/view? This worked for me on `Laravel 5.2` but doesn't seem to on `Laravel 5.3+`. Since you're specifying `Laravel 5.5`, I must be doing something wrong? – Wouter Vanherck Dec 14 '18 at 10:45
  • i have placed this code on app/Http/ExampleController.php – Zarkys Salas May 30 '19 at 05:33
5

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hamid Parchami
  • 7,319
  • 2
  • 18
  • 22
3

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.

MacTavish
  • 59
  • 8
3

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
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
HabteSoft
  • 101
  • 1
  • 2
3

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'),

];

3- Run these tow commands in terminal:

php artisan config:clear
php artisan config:cache

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

AnasSafi
  • 5,353
  • 1
  • 35
  • 38
2

In Controller

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

In blade.view

{{$_ENV['IMAP_HOSTNAME_TEST']}}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anandan K
  • 1,380
  • 2
  • 17
  • 22
2

In Laravel 7 I access .env variables like this.

You already have a file called services.php inside config folder.

define a new array like below

    'env_var'=>[
        'host' => env('DB_HOST'),
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        'database' => env('DB_DATABASE'),
    ]

now run php artisan config:cache

inside your controller import use Illuminate\Support\Facades\Config;

Now you can access like these

        $server = Config::get('services.env_var.host');
        $username = Config::get('services.env_var.username');
        $password = Config::get('services.env_var.password');
        $database = Config::get('services.env_var.database');

I hope it help someone.

Zia
  • 506
  • 3
  • 20
1

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');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rajib
  • 392
  • 4
  • 16
0

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.

Yuvraj Hinger
  • 198
  • 1
  • 6
0

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 ?

Gencix
  • 13
  • 3