Laravel遍历用户枚举值报错:Attempt to read property on string
错误原因分析
- 控制器查询逻辑错误:你用
DetailUser::find($user['id'])是根据DetailUser的主键id查找记录,但实际应该通过关联字段user_id来匹配当前用户的详情,这会导致要么找不到记录($detail_user为null),要么匹配到错误的记录。 - 视图循环逻辑错误:你试图遍历单个
DetailUser模型实例,这会把模型的属性键值对当作遍历项,此时$detail_user_item是字符串/数值类型,自然无法读取->productive_status属性。
修复步骤
步骤1:修正控制器中获取$detail_user的代码
将查询逻辑改为通过user_id匹配当前用户的详情记录:
// UserController.php $role = Role::all()->pluck('title','id'); $type_user = TypeUser::orderBy('name', 'asc')->get(); $user->load('role'); // 改为通过user_id查询关联的DetailUser记录 $detail_user = DetailUser::where('user_id', $user->id)->first(); return view('pages.backsite.management-access.user.edit', compact('user', 'role', 'type_user','detail_user'));
如果你的User模型和DetailUser模型已定义一对一关联(推荐更简洁的写法):
在User.php中添加关联:
public function detailUser() { return $this->hasOne(DetailUser::class); }
然后控制器中直接调用关联:
$detail_user = $user->detailUser;
步骤2:修正视图中的下拉框循环逻辑
你需要遍历枚举的所有可选值(而非单个模型实例),以下两种方式任选其一:
方式一:直接在视图中写死枚举选项(简单直接)
<select name="productive_status" id="productive_status" class="form-control select2" required> <option value="" disabled selected>Choose</option> {{-- 遍历枚举的所有可选值 --}} @foreach(['Productive','Pre Retirement','Retired'] as $status) <option value="{{ $status }}" {{ ($detail_user?->productive_status == $status) ? 'selected' : '' }}>{{ $status }}</option> @endforeach </select> @if($errors->has('productive_status')) <p style="font-weight: bold; color: red;">{{ $errors->first('productive_status') }}</p> @endif
注:$detail_user?->productive_status的写法是为了处理$detail_user为空的情况(比如用户还未创建详情记录),避免空对象报错。
方式二:在模型中定义常量复用(更易维护)
在DetailUser.php中添加枚举常量:
// DetailUser.php protected $fillable = [ // ... 原有字段 ]; // 定义生产状态枚举常量 const PRODUCTIVE_STATUSES = ['Productive','Pre Retirement','Retired'];
然后在视图中直接调用该常量:
<select name="productive_status" id="productive_status" class="form-control select2" required> <option value="" disabled selected>Choose</option> @foreach(\App\Models\DetailUser::PRODUCTIVE_STATUSES as $status) <option value="{{ $status }}" {{ ($detail_user?->productive_status == $status) ? 'selected' : '' }}>{{ $status }}</option> @endforeach </select> @if($errors->has('productive_status')) <p style="font-weight: bold; color: red;">{{ $errors->first('productive_status') }}</p> @endif
内容的提问来源于stack exchange,提问作者Timotius Hadi Pratama
相关产品推荐
相关产品推荐

