Laravel 5 - env() 总是返回 null

2024-08-10php开发问题
7

本文介绍了Laravel 5 - env() 总是返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我试图找出为什么我的 env() 助手总是返回 null.这会导致麻烦,尤其是在 app.php 文件中,默认情况下广泛使用 env() 帮助程序.也许有什么神秘的服务器设置?

I try to find out why my env() helper always returns null. This causes trouble especially in app.php file, where are env() helpers widely used by default. Perhaps any mysterious server setting?

我的环境文件:

APP_ENV=production
APP_KEY=base64:mymagickey=
APP_DEBUG=false
APP_LOG_LEVEL=info
APP_URL=http://www.example.com

etc...

编辑 - 我尝试了以下:

php artisan cache:clear
php artisan view:clear
php artisan config:cache

当然,我正在使用这样的 env 助手:env('APP_ENV')

and ofcourse, i am using env helper like this: env('APP_ENV')

但仍然没有成功.奇怪的是,$_ENV php 变量包含 .env 文件中的每个变量.

But still no success. The wierd part is, that $_ENV php variable contains every single variable from .env file.

推荐答案

env(...) 缓存配置后函数将无法工作.(从 laravel 5.2 到当前 5.7)

env(...) function will not work after you cached the config. (starting from laravel 5.2 till current 5.7)

Laravel 文档说

如果您在部署期间使用 config:cache 命令,则必须确保仅从配置文件中调用 env 函数,而不是从应用程序中的任何其他位置.

If you are using the config:cache command during deployment, you must make sure that you are only calling the env function from within your configuration files, and not from anywhere else in your application.

所以正确的答案是

如果您从应用程序中调用 env,强烈建议您将正确的配置值添加到配置文件中,然后从该位置调用 env,从而允许您将 env 调用转换为配置调用.

If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your env calls to config calls.

我从同一个文档

但为了快速修复,这样做可以:

But for a quick fix this will do:

php artisan config:clear

现在应该清楚为什么,当您尝试 config:cache 时,它没有帮助,即使它在缓存之前清除了配置.

And now it should be clear why, when you tried config:cache, it did not help, even though it clears the config prior to caching.

这篇关于Laravel 5 - env() 总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

PHP实现DeepL翻译API调用
DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以...
2025-08-20 php开发问题
168

PHP通过phpspreadsheet导入Excel日期数据处理方法
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的...
2024-10-23 php开发问题
287

mediatemple - 无法使用 codeigniter 发送电子邮件
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)...
2024-08-23 php开发问题
11

Laravel Gmail 配置错误
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)...
2024-08-23 php开发问题
16

将 PHPMailer 用于 SMTP 的问题
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)...
2024-08-23 php开发问题
4

关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)...
2024-08-23 php开发问题
17