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

前端之家收集整理的这篇文章主要介绍了Laravel:视图中的未定义偏移量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的对象.

由于您拥有Eloquent Collection,因此您可以使用其各种功能.其中一个是find(),用于通过id检索一个项目

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

猜你在找的Laravel相关文章