【发布时间】:2020-12-30 14:33:07
【问题描述】:
那是我的控制器:
public function index($slug_categoryName){
$categories=Categories::where('slug' ,$slug_categoryName)->firstOrFail();
$lower_categories=Categories::where('top_id', $categories->id)->get();
$products=$categories->products;
return view('category' ,compact('categories' ,'lower_categories' ,'products'));
}
我的刀片文件:
@foreach ($products as $product)
<h5><a class="ps-product__name" href="product-default.html">{{ $product->product_name }}</a></h5>
@endforeach
我的产品型号
public function products(){
return $this ->balongsToMany('App\Models\Products' , 'category_products');
}
我的类别模型
public function categories(){
return $this ->balongsToMany('App\Models\Categories' , 'category_products');
}
当我保存并刷新页面时出现错误---> 为 foreach() 提供的参数无效(查看:C:\wamp\www\BootcampProject\resources\views\category.blade.php)
【问题讨论】:
-
检查
$products后面的变量$products = $category-> products;不应该为空 -
并在循环之前添加
@if (count($products))。这样可以避免错误。
标签: laravel