Laravel 10的Facades\Process无法识别git命令:系统PATH未加载
Laravel 10 Process组件无法调用Git的问题解决
问题描述
在Windows 11系统的VSCode中开发Laravel 10应用,编写了用于获取应用Git版本信息的中间件,代码如下:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Process; use Symfony\Component\HttpFoundation\Response; class AppVersion { /** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { $label = "V"; $version = "0.1.0"; // Get version string from git $hash = Process::run('git log --pretty="%h" -n1 HEAD')->output(); $date = Process::run('git log -n1 --pretty=%ci HEAD')->output(); $version_string = "test"; config(['app.version' => $version_string]); return $next($request); } }
执行时通过->errorOutput()得到报错:
'git' is not recognized as an internal or external command, operable program or batch file.
Process::run可正常执行DIR等基础命令,且Git已安装并配置到系统PATH,终端中可正常调用。执行dd(Process::run("path")->output());得到输出:
"PATH=(null)"
解决方法
1. 手动传递系统PATH到Process调用
Laravel的Process组件在Windows环境下不会自动继承系统PATH,可手动获取系统PATH并传入Process的环境变量参数:
// 获取系统PATH变量 $systemPath = getenv('PATH'); // 调用Git命令时传入环境变量 $hash = Process::run('git log --pretty="%h" -n1 HEAD', [], ['PATH' => $systemPath])->output(); $date = Process::run('git log -n1 --pretty=%ci HEAD', [], ['PATH' => $systemPath])->output();
2. 全局配置Process默认环境变量
若不想每次调用都重复传入PATH,可在App\Providers\AppServiceProvider的boot方法中添加全局宏:
use Illuminate\Support\Facades\Process; public function boot() { Process::macro('withSystemPath', function () { return $this->env(['PATH' => getenv('PATH')]); }); }
后续调用Process时,直接使用宏简化代码:
$hash = Process::withSystemPath()->run('git log --pretty="%h" -n1 HEAD')->output();
3. 确保VSCode加载最新系统环境变量
VSCode可能未正确加载系统PATH的更新,尝试以下操作:
- 完全关闭并重启VSCode
- 以管理员身份启动VSCode
- 在VSCode终端中执行
echo %PATH%,确认Git所在路径已包含其中
4. 直接指定Git完整路径
如果上述方法无效,可直接使用Git的完整执行路径调用:
// 根据实际安装路径调整 $gitPath = '"C:\Program Files\Git\bin\git.exe"'; $hash = Process::run("$gitPath log --pretty=\"%h\" -n1 HEAD")->output(); $date = Process::run("$gitPath log -n1 --pretty=%ci HEAD")->output();
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

