Laravel电商项目报错:Attempt to read property "id" on integer 求助
问题解决:Laravel遍历商品属性报错“Attempt to read property "id" on integer”
问题根源
你犯了两个关键错误:
- 把整个Product模型对象转成了数组,
$attributes_data里包含的是商品本身的所有字段(比如id、名称等)以及嵌套的attributes数组,直接遍历$attributes_data时,循环拿到的是商品的单个字段值(比如第一个循环的$data就是商品的id,是个整数),自然不能用->id访问属性。 - 没必要重复查询商品,
Product::where(...) ->with('attributes')->first()已经拿到了包含属性的商品对象,后续的product::find($id)完全多余。
修正方案(推荐用Eloquent模型对象,更符合Laravel规范)
第一步:修改控制器代码
public function add_product_attributes($id) { // 用firstOrFail确保找不到商品时直接返回404,避免后续报错 $product = Product::where(['id' => $id])->with('attributes')->firstOrFail(); // 直接把商品对象传给视图,不需要转数组 return view('admin.add_product_attributes', compact('product')); }
第二步:修改视图代码
直接遍历商品的attributes关联集合,每个元素是Attribute模型对象,用->访问属性:
@foreach ($product->attributes as $attribute) <tr> <th scope="row">{{ $attribute->id }}</th> <td>{{ $attribute->category_id }}</td> <td>{{ $attribute->product_id }}</td> <td>{{ $attribute->sku }}</td> <td>{{ $attribute->size }}</td> <td>{{ $attribute->price }}</td> <td>{{ $attribute->stock }}</td> </tr> @endforeach
如果坚持用数组的方案(不推荐)
如果你一定要用数组操作,需要单独提取出attributes数组:
控制器修改:
public function add_product_attributes($id) { $product = Product::where(['id' => $id])->with('attributes')->firstOrFail(); // 只把attributes关联转成数组 $attributes_data = $product->attributes->toArray(); return view('admin.add_product_attributes', compact('product', 'attributes_data')); }
视图修改(数组用[]访问键):
@foreach ($attributes_data as $data) <tr> <th scope="row">{{ $data['id'] }}</th> <td>{{ $data['category_id'] }}</td> <td>{{ $data['product_id'] }}</td> <td>{{ $data['sku'] }}</td> <td>{{ $data['size'] }}</td> <td>{{ $data['price'] }}</td> <td>{{ $data['stock'] }}</td> </tr> @endforeach
内容的提问来源于stack exchange,提问作者Ahmad Raza
相关产品推荐
相关产品推荐

