Laravel:视图 index.blade.php 中的未定义偏移
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27525334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: Undefined offset in view index.blade.php
提问by Nat Naydenova
In my routes I have this route defined as:
在我的路线中,我将此路线定义为:
// app/routes.php
Route::resource('CharacterController');
The corresponding method in the controller is:
在控制器中对应的方法是:
// app/controllers/CharacterController.php
public function index(){
$characters = Character::all();
$houses = House::all();
return View::make('characters.index')->with(array('characters'=>$characters, 'houses' => $houses));
}
Finally, in the view:
最后,在视图中:
// app/views/characters/index.blade.php
#this fires an error:
{{ $houses[$characters->house_id]->name }}
# at the same time this gives correct result:
{{ $houses[1]->name }}
# and this IS equal to 1:
{{ $characters->house_id }}
采纳答案by lukasgeiter
You can't use the id
as index of the array to access the object with given id.
您不能使用id
数组的as 索引来访问具有给定 id 的对象。
Since you have an Eloquent Collection you can use its various functions. One of them being find()
for retrieving one item by id
因为你有一个 Eloquent Collection,你可以使用它的各种功能。其中之一find()
用于检索一项id
{{ $houses->find($characters->house_id)->name }}