Reputation: 100
ErrorException: Trying to get property of non-object -- laravel 5.3
I'm getting trouble in getting the data from foreign key . already make relation between 2 tables, but still error gave me this Trying to get property of non-object
Controller
public function show($id){
$activiter = Activiter::find($id);
return view('activiter.show',compact('activiter'));
}
show.blade.php
@foreach($activiter as $data)
@if($data->eleves)
<td>
{{ $data->eleves->nom }}
</td>
<td>
{{ $data->eleves->prenom }}
</td>
<td>
{{ $data->eleves->date_naissance }}
</td>
@endif
@endforeach
Model
public function eleves(){
return $this->hasMany('App\Eleve');
}
Upvotes: 1
Views: 2063
Reputation: 17658
Activiter::find($id)
returns a Model object so you can't foreach it.
Your blade file should be as:
@foreach($activiter->eleves as $data)
<td>
{{ $data->nom }}
</td>
<td>
{{ $data->prenom }}
</td>
<td>
{{ $data->date_naissance }}
</td>
@endforeach
And you should use findOrFail()
to confirm that data is fetched correctly as:
`$activiter = Activiter::findOrFail($id);`
Upvotes: 1