Reputation: 63
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:
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
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