Laravel get Eloquent relation by same name as its attribute

心已入冬 提交于 2019-12-01 23:35:27

You shouldn't use the same name for the both relationship and column name, else you'll receive always the column name so try to edit one of them, I think the easiest one here is the relationship name :

public function programmeObj() {
    return $this->belongsTo('App\Programme', 'programme', 'id');
}

Then call it as :

echo $shoot->programmeObj;

NOTE : But if you want to follow conventions you should replace the name attribute by programme_id so :

public function programme() {
    return $this->belongsTo('App\Programme', 'programme_id', 'id');
}

Hope this helps.

To achieve what you after you will need to do the following:

$shoot = Shoot:where('id','=',1)->with('programme')->first();
$variable = $shoot->programme; // returns 1
$obj = $page->getRelationValue('programme') // returns App\Programme object.

This will returns always the column in your database if it exists, that's ID 1.

When you call dump($shoot); you should get the array with all attributes. But when you run the following you should get the name:

Your model:

public function programmeData() {
    return $this->belongsTo('App\Programme', 'programme', 'id');
}

And your controller:

$shoot = Shoot:where('id','=',1)->first();
return $shoot->programmeData->name; // returns name

Hope this works!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!