【问题标题】:Laravel: Undefined offset in view index.blade.phpLaravel:视图 index.blade.php 中未定义的偏移量
【发布时间】:2014-12-17 20:17:57
【问题描述】:

在我的路线中,我将此路线定义为:

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

【问题讨论】:

  • 这是因为 $characters->house_id 是一个字符串吗?试试 intval() 看看会发生什么。
  • @Joe 谢谢,已经尝试过了,但不幸的是给出了相同的未定义偏移错误

标签: php laravel blade


【解决方案1】:

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

既然你有一个 Eloquent Collection,你就可以使用它的各种功能。其中之一是find() 用于通过id 检索一项

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

【讨论】:

  • 工作,谢谢:) 但是如果我在视图中调用find(),那么在控制器中获取all() 房屋有什么意义?我的意思是我可以做{{ House::find($character->house_id)->name }},因为这是在foreach() 循环中,这是否意味着它将对房屋表进行N 次数据库调用?我很困惑
  • 不完全是。 House::find() 在 DB $houses->find() 上运行您已经获取的房屋集合。所以它只是在内存中执行搜索,而无需再次查询数据库。
  • 知道了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-04-24
  • 2021-07-12
  • 2014-06-25
  • 1970-01-01
  • 2015-12-20
  • 2020-01-02
  • 2021-07-06
  • 1970-01-01
相关资源
最近更新 更多