Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get Eloquent relation by same name as its attribute

I have database tables like this:

shoot: id, name, programme
programme: id, name

The eloquent relationship in the shoot is defined like this:

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

When using dd(), I can see this is working correctly:

dd(Shoot:where('id','=',1)->with('programme')->first());
// prints the object with programme listed under the relationship

However when I eager-load the shoot and attempt to get the programme object, I retrieve the shoot attribute "programme" instead. E.g.:

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

Is there a solution to this without having to rewrite masses of the codebase?

like image 389
kirgy Avatar asked Jan 04 '17 09:01

kirgy


2 Answers

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.

like image 94
Zakaria Acharki Avatar answered Oct 20 '22 01:10

Zakaria Acharki


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.
like image 38
Vlad Vladimir Hercules Avatar answered Oct 20 '22 01:10

Vlad Vladimir Hercules