Laravel - 访问 .env 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51987140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - accessing .env variables
提问by LeBlaireau
I tried to get the environment variable from the .env in my root with
我试图从我的根目录中的 .env 中获取环境变量
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
它在 .env 中
APP_NAME=Laravel
APP_ENV=local
How can I get access to it?
我怎样才能访问它?
回答by Devon
With Laravel, you should avoid environmental variables outside of your configuration files.
使用 Laravel,您应该避免配置文件之外的环境变量。
In your config files, you can use environmental variables, example in config/app.php:
在您的配置文件中,您可以使用环境变量,例如 config/app.php:
'env' => env('APP_ENV', 'production'),
Then you can access this using the config helper: config('app.env')
.
然后您可以使用配置助手访问它: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.
这允许您缓存您的配置并仍然访问这些值,因为一旦您的配置被缓存env('APP_ENV')
将不再工作。
回答by Sunil Kumar
Route::get('/test', function () {
return "it is".config('app.name');
});
回答by netzding
laravel provides a global helper function for this kind of task
laravel 为此类任务提供了一个全局辅助函数
$val = config('app.something');
you can also set new values with the following method
您还可以使用以下方法设置新值
config(['app.something' => 'cat']);
for your particular task it would be
对于您的特定任务,它将是
$val = config('app.env');
or to determine the env globally
或在全局范围内确定 env
$environment = App::environment();
i hope this helps, have a nice one!
我希望这会有所帮助,祝你好运!
回答by user7747472
use env('ENVKEY')
Don't forget to clear cache sometime it cause because of cache.
使用 env('ENVKEY')
不要忘记清除缓存,因为缓存有时会导致它。
php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan config:clear
php artisan cache:clear
composer dump-autoload
Formore info look at the doc
有关更多信息,请查看文档
回答by Akbar Mirsiddikov
App::environment()
try this please
请试试这个
回答by GAURAV VAGHELA
just run this commands in cmd.
只需在 cmd 中运行此命令。
php artisan config:cache
php工匠配置:缓存
then
然后
php artisan config:clear
php工匠配置:清除
then
然后
php artisan cache:clear
php artisan 缓存:清除
回答by suzan
As per the Laravel Documentation on Environment Configuration,
根据 Laravel环境配置文档,
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.
当您的应用程序收到请求时,此文件中列出的所有变量都将加载到 $_ENV PHP 超级全局变量中。您可以使用 env 助手从这些变量中检索值。
So, it is possible to access the variable as
因此,可以将变量访问为
$_ENV['envKey'];