简体   繁体   English

在foreach刀片视图中出现laravel 5.6错误

[英]laravel 5.6 error in a foreach blade view

During an iteration of an array of array I have this error: 在数组的数组迭代期间,我遇到此错误:

Invalid argument supplied for foreach() (View: C:\\xampp\\htdocs\\smartcalws\\resources\\views\\location\\index.blade.php 为foreach()提供的参数无效(视图:C:\\ xampp \\ htdocs \\ smartcalws \\ resources \\ views \\ location \\ index.blade.php

Below the code in the view: 视图中的代码下方:

 @foreach($Nations as $e)
                <tr>
                  <th scope="row">{{$e->id}}</th>
                  <td>{{$e->name}}</td>   
 @foreach($e->districts as $d)
                  <td>{{$d->name}}</td>
      @endforeach   
 @endforeach

Can anyone know the why? 谁能知道为什么?

In the controller if I execute the foreach all work fine with the echo: 在控制器中,如果我执行foreach,则所有工作都可以通过echo正常工作:

 foreach($Nations as $e){
   foreach($e->districts as $d){
     echo $d->name;
    }
  }

All nations have districts. 所有国家都有地区。 The echo print all the districts. 回显将打印所有区域。 I thinks that the problem is in the blade page... 我认为问题出在刀片页面上...

return view('Nations.index',compact('Nations',$Nations));

The blade looks correct. 刀片看起来正确。 Make sure you are passing the correct parameter in Nations to the blade view. 确保在“ Nations中将正确的参数传递给刀片视图。 It might be complaining about the first foreach. 它可能在抱怨第一个foreach。 You need something like the following in the controller. 您在控制器中需要以下内容。

return view('yourview', [
    'Nations' => $Nations
]);

Perhaps also good to be consistent with working with lowercase variable names. 与使用小写变量名称保持一致可能也很好。 Perhaps you are passing the key nations but wanting to use Nations . 也许您正在通过关键nations但想要使用Nations

Your problem is sending data to view 您的问题是发送数据以查看

compact('Nations', $Nations) // It's wrong

Try these ways : 尝试以下方法:

return view('Nations.index', compact('Nations'));
return view('Nations.index', ['Nations' => $Nations]);
return view('Nations.index')->withNations($Nations);
return view('Nations.index')->with('Nations', $Nations);

Make sure you pass the array to blade. 确保将阵列传递到刀片。

Also, you should put a check around your loops, if the array count is > 0 另外,如果数组计数> 0,则应检查循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM