0
votes

I have problem laravel relation. I use method with() in my controller and belongsTo in my model. My relation is normaly but if i get parent data this the problems.

my models

public function pekerjaan()
{
    return $this->belongsTo('App\Pekerjaan', 'pekerjaan', 'id');
}

This my controller

 $data = Anggota::with('pekerjaan')->where('nik',$nik)->first();
 return $data;

I want to get column 'nama_pekerjaan' in my relation 'pekerjaan' I want to get column 'nama_pekerjaan' in my relation 'pekerjaan'

if i use return $data->pekerjaan->nama_pekerjaan; show errors enter image description here

1

1 Answers

1
votes

You have a column named pekerjaan and a relationship named pekerjaan. Laravel treats column names more than relationships. So yo can get the column value(id of pekerjaan) with the property pekerjaan. Give another name to your relationship to fix this alias problem.

In your model.

function pekerjaan_parent(){
   return $this->belongsTo('App\Pekerjaan', 'pekerjaan', 'id');
}

In you function

return $data->pekerjaan_parent->nama_pekerjaan;