Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
LeBlaireau Avatar asked Aug 23 '18 13:08

LeBlaireau


People also ask

Can I use variables in .env file?

You can set default values for environment variables using a .env file, which Compose automatically looks for in project directory (parent folder of your Compose file). Values set in the shell environment override those set in the .env file.

For what do the .env is used in Laravel?

Laravel's default .env file contains some common configuration values that may differ based on whether your application is running locally or on a production web server. These values are then retrieved from various Laravel configuration files within the config directory using Laravel's env function.

How do I change environment variables in Laravel dynamically?

A simple way to update the . env key value in laravel is to add the below code in the controller function where you want to change . env values. $key = 'VARIABLE_NAME'; $value = 'NEW VALUE'; file_put_contents(app()->environmentFilePath(), str_replace($key .


2 Answers

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.

like image 85
Devon Avatar answered Nov 08 '22 13:11

Devon


Route::get('/test', function () {
    return "it is".config('app.name');
});
like image 37
Sunil Kumar Avatar answered Nov 08 '22 12:11

Sunil Kumar