Laravel:视图索引中未定义的偏移量.blade.php


Laravel: Undefined offset in view index.blade.php

在我的路线中,我把这条路线定义为:

// app/routes.php
Route::resource('CharacterController');

控制器中的对应方法是:

// app/controllers/CharacterController.php
public function index(){
    $characters = Character::all();
    $houses = House::all();
    return View::make('characters.index')->with(array('characters'=>$characters, 'houses' => $houses));
}

最后,在以下观点中:

// 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 }}

不能使用 id 作为数组的索引来访问具有给定 id 的对象。

由于您有一个雄辩的收藏,您可以使用它的各种功能。其中之一是find()用于通过id检索一个项目

{{ $houses->find($characters->house_id)->name }}