Search code examples
laravellaravel-5eloquentlaravel-5.3

Error in Relationship of tables


Im having a error when i try to get some data between 2 tables using eloquent. The error that is giving me is:

Error:
Trying to get property of non-object (View: 

This is my app information

DB:
survey:
- id;
- template_id;
- title;


templates:
- id;
- name;
- internal_name;

SurveyModel:
 public function theme(){

        return $this->hasOne(Template::class, 'template_id','id');
}


View:

@foreach($surveys->reverse() as $survey)

        <tr>
        <td>{{$survey->template_id->theme}}</td>

</tr>
@endforeach

Solution

  • You should use the them directly :

    <td>{{$survey->theme}}</td>
    

    And that will return the related Template model, instead you could get the attribute you want, example :

    <td>{{$survey->theme->name}}</td>
    

    Hope this helps.