'Laravel - accessing .env variables

I tried to get the environment variable from the .env in my root with

Route::get('/test', function () {
    return "value is". getenv('APP_ENV');
});

and

Route::get('/test', function () {
    return "it is". env('APP_ENV');
});

It is in .env

APP_NAME=Laravel
APP_ENV=local

How can I get access to it?



Solution 1:[1]

Route::get('/test', function () {
    return "it is".config('app.name');
});

Solution 2:[2]

With Laravel, you should avoid environmental variables outside of your configuration files.

In your config files, you can use environmental variables, example in config/app.php:

'env' => env('APP_ENV', 'production'),

Then you can access this using the config helper: config('app.env').

This allows you to cache your configuration and still access these values, since env('APP_ENV') will no longer work once your config is cached.

Solution 3:[3]

use env('ENVKEY') Don't forget to clear cache sometime it cause because of cache.

php artisan config:clear php artisan cache:clear composer dump-autoload

Formore info look at the doc

Solution 4:[4]

just run this commands in cmd.

php artisan config:cache

then

php artisan config:clear

then

php artisan cache:clear

Solution 5:[5]

As per the Laravel Documentation on Environment Configuration,

All of the variables listed in this file will be loaded into the $_ENV PHP super-global when your application receives a request. You may use the env helper to retrieve values from these variables.

So, it is possible to access the variable as

$_ENV['envKey'];

Solution 6:[6]

laravel provides a global helper function for this kind of task

$val = config('app.something');

you can also set new values with the following method

config(['app.something' => 'cat']);

reference

for your particular task it would be

$val = config('app.env');

or to determine the env globally

$environment = App::environment();

i hope this helps, have a nice one!

Solution 7:[7]

 App::environment()

try this please

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sunil Kumar
Solution 2 Devon
Solution 3 user7747472
Solution 4
Solution 5 suzan
Solution 6
Solution 7 Jignesh Joisar