nielsv
nielsv

Reputation: 6800

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?

Upvotes: 122

Views: 309078

Answers (18)

M Umar Habib
M Umar Habib

Reputation: 19

Have you done php artisan config:cache? If so try running php artisan config:clear in your terminal. Also if you are using php artisan serve you need to kill that process and start it again to see the changes in .env file.

Upvotes: 1

Adnan Afridi
Adnan Afridi

Reputation: 11

In my controller, env('KEY') was consistently returning null, even after running php artisan config:cache. The only solution that worked was executing php artisan optimize:clear, which cleared all events, views, cache, routes, config, and compiled files. After that env('KEY') started working in my Controller.

Upvotes: 1

Actually, you missed an entry in config/app.php:

.env file

IMAP_HOSTNAME_TEST=imap.gmail.com

Create into file config/app.php this entry:

'imap_host_name' => env('IMAP_HOSTNAME_TEST'),

And now, you can use in your code:

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

Upvotes: 1

Grant
Grant

Reputation: 6309

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 optimize:clear 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.

Upvotes: 98

Farukh Ali
Farukh Ali

Reputation: 11

env('MAIL_USERNAME', '');

if not working hit command: php artisan config:clear

Upvotes: 0

Zia
Zia

Reputation: 683

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.

Upvotes: 2

AnasSafi
AnasSafi

Reputation: 6224

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

Upvotes: 3

HabteSoft
HabteSoft

Reputation: 121

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

Upvotes: 3

Gencix
Gencix

Reputation: 13

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 ?

Upvotes: 0

Yuvraj Hinger
Yuvraj Hinger

Reputation: 368

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.

Upvotes: 0

MacTavish
MacTavish

Reputation: 59

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.

Upvotes: 3

Rajib
Rajib

Reputation: 592

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

Upvotes: 1

Hamid Parchami
Hamid Parchami

Reputation: 7689

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.

Upvotes: 5

Masum Ahmed Sarkar
Masum Ahmed Sarkar

Reputation: 1019

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

Upvotes: 100

Anandan K
Anandan K

Reputation: 1438

In Controller

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

In blade.view

{{$_ENV['IMAP_HOSTNAME_TEST']}}

Upvotes: 3

Zarkys Salas
Zarkys Salas

Reputation: 121

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

Upvotes: 6

Basheer Kharoti
Basheer Kharoti

Reputation: 4292

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'];

Upvotes: 33

Chetan Ameta
Chetan Ameta

Reputation: 7896

Try it with:

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

Upvotes: 122

Related Questions