Laravel 9 读取category->name报Attempt to read property "name" on null错误
问题描述
我在使用Laravel 9开发简易库存系统时,需要关联category、brand和product三张表,已编写好模型关联关系及查询逻辑,但在视图中调用{{ $item->category->name }}时出现「Attempt to read property "name" on null」错误。
相关代码片段
Product模型
protected $table = 'products'; protected $primaryKey = 'id'; protected $fillable = ['barcode_no', 'productname', 'cat_id', 'brand_id', 'price']; public function category() { return $this->belongsTo(Category::class); } public function brand() { return $this->belongsTo(Brand::class); }
Category模型
protected $table = 'categories'; protected $primaryKey = 'id'; protected $fillable = ['name', 'status']; public function products() { return $this->hasMany(Product::class, 'cat_id', 'id'); }
Brand模型
protected $table = 'brands'; protected $primaryKey = 'id'; protected $fillable = ['name', 'status']; public function products() { return $this->hasMany(Product::class, 'brand_id', 'id'); }
产品视图
@foreach($products as $item) <tr> <td>{{ $loop->iteration }}</td> <td>{{ $item->barcode_no }}</td> <td>{{ $item->productname }}</td> <td>{{ $item->category->name }}</td> <td>{{ $item->brand->name }}</td> </tr> @endforeach
Product控制器
public function index(Request $request) { $keyword = $request->get('search'); $perPage = 25; if (!empty($keyword)) { $products = Product::where('barcode_no', 'LIKE', "%$keyword%") ->orWhere('productname', 'LIKE', "%$keyword%") ->orWhere('cat_id', 'LIKE', "%$keyword%") ->orWhere('brand_id', 'LIKE', "%$keyword%") ->orWhere('price', 'LIKE', "%$keyword%") ->latest()->paginate($perPage); } else { $products = Product::latest()->paginate($perPage); } return view('admin.products.index', compact('products')); }
解决方案
修正关联外键参数:Laravel默认以关联方法名+
_id作为外键(比如category()对应category_id),但你的产品表用的是cat_id和brand_id,需在belongsTo中明确指定外键:// Product模型修改关联方法 public function category() { return $this->belongsTo(Category::class, 'cat_id'); } public function brand() { return $this->belongsTo(Brand::class, 'brand_id'); }预加载关联数据:在控制器查询时用
with()预加载分类和品牌,既避免N+1查询问题,也确保关联数据正确加载:// 搜索场景 $products = Product::with(['category', 'brand']) ->where('barcode_no', 'LIKE', "%$keyword%") ->orWhere('productname', 'LIKE', "%$keyword%") ->orWhere('cat_id', 'LIKE', "%$keyword%") ->orWhere('brand_id', 'LIKE', "%$keyword%") ->orWhere('price', 'LIKE', "%$keyword%") ->latest()->paginate($perPage); // 普通场景 $products = Product::with(['category', 'brand'])->latest()->paginate($perPage);视图处理null情况:即使关联正确,也可能存在产品未分配分类/品牌的情况,用可选链或默认值避免报错:
<td>{{ $item->category?->name ?? '无分类' }}</td> <td>{{ $item->brand?->name ?? '无品牌' }}</td>检查数据库数据:确认products表中
cat_id、brand_id的值是否存在对应的categories/brands表记录,避免无效外键或null值。
内容的提问来源于stack exchange,提问作者abi jega
相关产品推荐
相关产品推荐

