Laravel Livewire渲染数据时出现Attempt to read property "investment_id" on array错误如何解决
问题原因
- 代码存在笔误:在
showInvestmentModal方法中赋值的属性为$investmentPopupClicked,但你定义的公共属性是$investmentModalClicked,名称不一致会导致模态框状态控制异常。 - 报错核心原因:
DB::select()返回的是stdClass对象数组,首次渲染时$item为对象可以用->正常访问属性;但Livewire的公共属性会在组件重渲染(如触发更新操作、心跳检测)时做序列化/反序列化处理,stdClass对象经过这个流程会被转为纯关联数组,再用->访问就会触发报错。
可行解决方案
方案一(最稳妥,推荐):统一使用数组访问
将查询结果转为关联数组存储,同步修改模板的取值语法:
- 修改组件中
investmentList的赋值逻辑:
public function showInvestmentModal($userId) { // 先修正笔误 $this->investmentModalClicked = true; $queryResult = DB::select('select id, date, investment_id, initial_investment, status ' . 'from investment_data ' . 'where user_id = ? ' . "and (status = 'ACTIVE' or status = 'INACTIVE')" . 'order by status asc', [$userId]); // 把stdClass对象数组转为关联数组 $this->investmentList = collect($queryResult)->toArray(); $this->emit('showInvestmentModal'); }
- 修改
investment-modal.blade.php中的取值语法:
<td>{{ $item['investment_id'] }}</td> <td>USD {{ $item['initial_investment'] }}</td> <td>{{ $item['status'] }}</td>
方案二(无需修改模板):转为Eloquent集合存储
Livewire支持对Eloquent集合做序列化/反序列化,转换后可以保持对象访问语法,不需要修改模板:
public function showInvestmentModal($userId) { $this->investmentModalClicked = true; $queryResult = DB::select('select id, date, investment_id, initial_investment, status ' . 'from investment_data ' . 'where user_id = ? ' . "and (status = 'ACTIVE' or status = 'INACTIVE')" . 'order by status asc', [$userId]); // 转为Eloquent集合 $this->investmentList = \Illuminate\Database\Eloquent\Collection::make($queryResult); $this->emit('showInvestmentModal'); }
内容的提问来源于stack exchange,提问作者aldr
相关产品推荐
相关产品推荐

