Laravel: Undefined offset in view index.blade.php

In my routes, I have this route defined as:

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

      

Corresponding method in controller:

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

      

+3


source to share


1 answer


You cannot use id

as an array index to access an object with a given ID.

Since you have an Eloquent Collection, you can use various functions. One is find()

to retrieve one itemid



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

      

+2


source







All Articles