Laravel中条件语句内$status变量未更新问题求助
问题解决步骤
核心问题分析
- 控制器判断逻辑错误:
DB::table()->get()返回的是Laravel集合对象,哪怕没有匹配数据,empty($records)也会返回false(因为集合实例本身是存在的),导致$status永远被设为exist。 - 模板冗余代码无效:
@else分支里的($status === 'not_exist')是多余的无效代码,会直接输出到页面,且逻辑完全没必要。
控制器代码修正
方案一:用集合的isEmpty()方法判断(适合多记录场景)
public function read(){ $records = DB::table('user_profiles') ->where('user_id', auth()->user()->id)->get(); // 改用集合自带的isEmpty()方法判断是否无数据 $status = $records->isEmpty() ? 'not_exist' : 'exist'; // 调试完成后,记得将变量传递给视图(替换成你的实际视图名) return view('profile.view', compact('status', 'records')); }
方案二:用first()获取单条记录(更适合单用户单档案场景)
通常一个用户对应唯一档案,用first()直接获取单个实例,判断是否为null更高效:
public function read(){ $profile = DB::table('user_profiles') ->where('user_id', auth()->user()->id)->first(); $status = is_null($profile) ? 'not_exist' : 'exist'; return view('profile.view', compact('status', 'profile')); }
Blade模板代码修正
去掉@else分支里的冗余代码,简化逻辑:
@if($status === 'exist') <button type="button" class="btn mb-3" data-bs-toggle="modal" data-bs-target="#edit-company-profile"> Edit Profile </button> @else <button type="button" class="btn mb-3" data-bs-toggle="modal" data-bs-target="#edit-company-profile"> Create Profile </button> @endif
内容的提问来源于stack exchange,提问作者m_imran79
相关产品推荐
相关产品推荐

