Laravel按ID读取表数据报错:Trying to get property of non-object
解决Laravel中「Trying to get property of non-object」错误
我一眼就看出问题出在哪了——你的新项目表主键是productid,但Laravel的模型默认会把id当作主键字段来查询,这就导致你用find($id)或者where('id', $id)根本找不到数据,返回的是null,视图里再去遍历这个null,自然就抛出「Trying to get property of non-object」的错误了。
下面是具体的修复步骤:
1. 修改Products模型,指定主键
打开App/Models/Products.php,添加代码告诉Laravel你的主键字段是productid:
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Products extends Model { // 指定表的主键字段 protected $primaryKey = 'productid'; // 如果你的productid不是自增整数类型,再加上下面这句 // public $incrementing = false; }
2. 优化控制器代码
现在find()方法会自动用productid查询了,同时注意几个细节:
find()返回单个模型实例,不是集合,变量名改成$product更合理- 你之前重复传递了
products变量,选一种方式即可 - 建议增加判断,避免找不到数据时直接报错
修正后的控制器代码:
public function showDetail($id) { // 现在会根据productid查询对应产品 $product = Products::find($id); // 找不到产品时返回404页面 if (!$product) { abort(404, '产品不存在'); } return view('sectiondetail', compact('product')); }
3. 修正视图代码
因为传递的是单个产品对象,不需要用@foreach遍历,直接使用$product即可:
<div class="productdetail"> <div id="thumbnail"> <img src="{{ $product->productpicture }}"> </div> <div id="productdescription"> <div id="name">{{ $product->productname }}</div> <br> <div> <b>Ingredients:</b> {{ $product->productdescription }} </div> <br> <button class="sim-button button24">Book</button> </div> </div>
为什么之前的代码无效?
- 旧项目主键是
id,刚好匹配Laravel模型的默认设置,所以find()能正常工作;新项目主键改成productid后,模型没更新配置,导致查询字段错误 - 你用
Products::where('id', $id)无效,是因为你的表根本没有id字段,原本应该写成where('productid', $id)->first(),不过指定主键后用find()更简洁
内容的提问来源于stack exchange,提问作者Steve Ruru
相关产品推荐
相关产品推荐

