【问题标题】:Invalid argument supplied for foreach() -laravel 8为 foreach() -laravel 8 提供的参数无效
【发布时间】: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-&gt; products;不应该为空
  • 并在循环之前添加@if (count($products))。这样可以避免错误。

标签: laravel


【解决方案1】:

这是因为当你调用$categories-&gt;products时,一些$categories可能没有products
在你的刀片文件中放这个:

@if($products)
    @foreach ($products as $product)
     <h5><a class="ps-product__name" href="product-default.html">{{ $product->product_name }}</a></h5>
    @endforeach
@endif

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2021-12-25
    • 2021-02-24
    • 2018-12-09
    • 1970-01-01
    • 2015-06-29
    • 2018-02-26
    • 2017-11-26
    • 2019-10-05
    相关资源
    最近更新 更多