Laravel执行cache:clear时request()相关异常问题排查
问题分析与解决
问题根源
执行php artisan cache:clear时处于命令行环境,此时没有HTTP请求上下文,request()->segment(1)无法获取到有效的路由分段值,返回空字符串(或null)。尝试访问$segments->$locale时,相当于访问stdClass::${''},自然触发"Undefined property"错误。
而浏览器环境下存在正常HTTP请求,request()->segment(1)能正确拿到locale值,所以代码运行正常。
修复方案
方案一:设置默认Locale并增加校验
给$locale设置默认值,同时校验该值是否存在于JSON解析后的对象中,避免无效访问:
public static function getSegments() { $json = file_get_contents(base_path().'/routes/segments/post.json', true); $segments = json_decode($json); $locale = request()->segment(1) ?? 'fr'; // 确保locale在segments对象中存在,不存在则 fallback到默认值 if (!property_exists($segments, $locale)) { $locale = 'fr'; } return $segments->$locale; }
方案二:判断命令行环境
利用Laravel内置方法识别命令行环境,直接为该场景指定Locale:
use Illuminate\Support\Facades\App; public static function getSegments() { $json = file_get_contents(base_path().'/routes/segments/post.json', true); $segments = json_decode($json); if (App::runningInConsole()) { $locale = 'fr'; // 命令行下强制使用默认Locale } else { $locale = request()->segment(1) ?? 'fr'; } return $segments->$locale; }
以上两种修改都能让代码在浏览器和artisan命令行环境下正常运行,避免触发错误。
内容的提问来源于stack exchange,提问作者Duddy67
相关产品推荐
相关产品推荐

