Wesley Shann
Wesley Shann

Reputation: 63

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:

All the 3 tables have the field 'nome'

The page in View will show:

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> {{$disciplina->nome}} </td>
            <td> {{$disciplina->professor}} </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> {{$disciplina->professor->nome}} </td>

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

Upvotes: 0

Views: 43

Answers (1)

user2094178
user2094178

Reputation: 9464

The following is incorrect:

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

If disciplinas table contains the foreign key professor_id, then the relationship should simply be:

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

Upvotes: 1

Related Questions