You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6调度任务中$_ENV为空,config()/env()可正常读取

Why is my $_ENV empty in Laravel scheduled tasks?

Hey there! I’ve run into this exact quirk with Laravel 5.x before, so let’s break down what’s going on and how to fix it.

What’s causing the empty $_ENV?

Laravel’s task scheduler runs commands in a slightly different context than regular CLI commands or HTTP requests:

  • When you run a command directly like php artisan process:job, the artisan bootstrap script loads your .env file using Dotenv, which populates the global $_ENV superglobal automatically.
  • When you trigger the scheduler via php artisan schedule:run, the framework boots up first, loads the environment variables into its own internal configuration store, but doesn’t sync those values to $_ENV. This is a design choice in Laravel 5.x to keep environment variable handling isolated and secure within the framework.

That’s why config() and env() still work—they pull values from Laravel’s internal store, not the global $_ENV.

Fixes to get $_ENV populated (or better alternatives)

Option 1: Sync Laravel’s environment variables to $_ENV

If you really need to use $_ENV, you can manually sync Laravel’s internal env variables at the start of your task:

// Inside your process:job command's handle() method
foreach (app('env')->all() as $key => $value) {
    $_ENV[$key] = $value;
}

Or you can reload the .env file directly using Dotenv to ensure full population:

$dotenv = new \Dotenv\Dotenv(base_path());
$dotenv->overload(); // This will overwrite existing $_ENV values if they exist

Option 2: Use Laravel’s native methods instead of $_ENV

A better practice (and more Laravel-friendly) is to avoid relying on $_ENV entirely. You can iterate over all environment variables using Laravel’s internal service:

// Get all environment variables
$allEnvVars = app('env')->all();

// Iterate and handle specific keys
foreach ($allEnvVars as $key => $value) {
    if (strpos($key, 'YOUR_TARGET_PREFIX') === 0) {
        // Process your specific keys here
    }
}

This approach keeps your code aligned with Laravel’s design and avoids issues with environment variable context.

Why does this work in HTTP/regular CLI but not scheduled tasks?

  • HTTP requests: The public/index.php entry file loads Dotenv early on, which populates $_ENV before the framework fully boots.
  • Regular CLI commands: The artisan script does the same as index.php—loads Dotenv and syncs to $_ENV before running your command.
  • Scheduled tasks: The scheduler boots the framework first, then executes each task in a sub-context where the initial Dotenv sync to $_ENV doesn’t happen automatically.

内容的提问来源于stack exchange,提问作者AsTeR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:15:07