Laravel 5.6调度任务中$_ENV为空,config()/env()可正常读取
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, theartisanbootstrap script loads your.envfile using Dotenv, which populates the global$_ENVsuperglobal 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.phpentry file loads Dotenv early on, which populates$_ENVbefore the framework fully boots. - Regular CLI commands: The
artisanscript does the same asindex.php—loads Dotenv and syncs to$_ENVbefore 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
$_ENVdoesn’t happen automatically.
内容的提问来源于stack exchange,提问作者AsTeR

