Laravel中重复遍历数组时报Trying to get property of non-object错误
你在控制器里已经把$categorie(分类集合)传递到视图了,代码如下:
public function ViewDemmandes(){ $listdemmande = Demmande::orderBy('created_at', 'DESC')->paginate(5); $listvillee=Ville::all(); $listcategorie=Categorie::all(); $listepublic=Publiccibles::all(); $villes = $listvillee; $demmande = $listdemmande; $categorie = $listcategorie; $pulics=$listepublic; return view("demmande.demmandes",compact('listepublic','demmande','villes','categorie')); }
然后你在视图里两处使用$categorie:
第一处(正常运行):
<select id="selectType" class="form-control"> @foreach ($categorie as $categorie ) <option value= {{$categorie->id}} >{{$categorie->nom}}</option> @endforeach </select>
第二处(报错):
<li><i class="material-icons">lightbulb_outline</i> Type : @foreach($categorie as $type) {{$type->nom}} @endforeach </li>
错误信息:
Trying to get property of non-object (View: C:\wamp\www\project\resources\views\demmande\demmandes.blade.php)
问题根源
你在第一个@foreach里犯了一个变量名冲突的低级错误:你把循环的单个项变量名也设成了$categorie,和原来的集合变量名完全一样!
当第一个foreach执行时,每次迭代都会把集合里的单个分类对象赋值给$categorie,循环结束后,原来的$categorie集合就被覆盖成了最后一个分类对象。这时候你在第二处再用@foreach($categorie as $type),本质上是在遍历单个对象,而不是集合——遍历对象会拿到它的属性值(比如字符串、数字),这些值不是对象,所以当你试图访问$type->nom时,就会抛出「Trying to get property of non-object」的错误。
解决方案
把第一个foreach的单个项变量名改成和集合不同的名字,比如$cat或者$categorieItem:
修改后的第一处代码:
<select id="selectType" class="form-control"> @foreach ($categorie as $cat ) <option value="{{ $cat->id }}">{{ $cat->nom }}</option> @endforeach </select>
这样原来的$categorie集合变量就不会被覆盖,第二处的@foreach($categorie as $type)就能正常遍历整个分类集合了。
另外给你个小建议:写Blade模板时尽量保持变量名语义化,集合用复数(比如$categories),单个项用单数(比如$category),这样能从根源避免这类变量名冲突的问题。比如控制器里可以把$categorie = $listcategorie;改成$categories = $listcategorie;,视图里对应改成@foreach($categories as $category),可读性会强很多~
内容的提问来源于stack exchange,提问作者Zakaria Mountassir

