louisav louisav - 4 months ago 36
PHP Question

Laravel 5.2 belongsTo relationship Trying to get property of non-object

I looked at some other similar posts, but can't seem to solve this one. New to Laravel.
I have my view:

@foreach($logged_jobs as $logged_job)
<li>{{ $logged_job->a_score->sport }}</li>
@endforeach


Model1:

class joblogs extends Model
{
public function a_score()
{
return $this->belongsTo('App\scores');
}
}


Model2:

class scores extends Model
{
public function loggs()
{
return $this->hasMany('App\joblogs');
}
}


I've tried naming the a_score() method several names.
If I only output
<li>{{ $logged_job }}</li>
it works, displays all the rows in the joblogs table, but when I try to add the relationship to get the name, it gives the error.

Scores data here
Logs data here

So view should read:
Tennis
Tennis
Tennis
Rugby
Rugby etc.

Answer

its because you need to specify the relation fields ...

public function a_score()
{
   return $this->belongsTo('App\scores', 'scores_id');
}

please review the documentation to learn more about the relations in Elouquent ...