Wednesday, March 8, 2017

Cannot acess data from Eloquent: Relationships, as well some data is not retrieved

I want to show my data from relation between tables in my view, where the relations are:

  • Curso 1 --- * Disciplina.
  • Disciplina * -- 1 Professor.

All the 3 tables have the field 'nome'

The page in View will show:

  • The field 'nome' of table 'Curso'.
  • A HTML table with 2 column:
    • The field 'nome' of table 'Disciplina'.
    • The field 'nome' of table 'Professor'.

But I'm having 2 problems:

  1. I get the data of 'Disciplina' that I need, but some of them don't show the data of associated 'Professor'.
  2. I got a error when I try to access the field 'nome' of 'Professor' from the 'Disciplina' when I try to list it in the table.

My 'Disciplina' Model

public function professor(){
    return $this->belongsTo('App\Model\Professor','id');
}

My Controller

$curso = Curso::find($id);
$curso->disciplinas();

foreach ($curso->disciplinas as $key => $disciplina) {
    $disciplina->professor;
}

return View::make('curso.showCurso')->with('curso', $curso);

My table in View

<tbody>
    @foreach ($curso->disciplinas as $key => $disciplina)
        <tr>
            <td>  </td>
            <td>  </td>
        </tr>
    @endforeach
</tbody>

This image show part of the table, where the first row are not showing the professor and the remaining rows are showing all fields from professor.

Table showing all fields of 'professor'

When I try to show the field 'nome' of 'Professor' I change the code for:

<td>  </td>

But when I do it I get this error "Trying to get property of non-object".



via sshann

Advertisement