T2theC
T2theC

Reputation: 540

Laravel: get Many-to-Many column data

Yo all,

I have a users relationship pivot db table as follows:

id | user_id | relation_id | relationship
1    4         2             tutor
1    4         3             parent

The table relates user with one-and-other for various reasons.

I am trying to get the relationship column within the $user. I have managed to pull the related users details no problem - $user->relations.

However, I just need to get the relationship - eg. Tutor or parent. I am getting no dice with $relative->pivot->relationship

Any ideas? Thanks for taking the time to help.

@foreach($user->relations as $index=>$relative)
    {{ $relative->first_name . ' ' . $relative->last_name}}
    {{ $relative->pivot->relationship }}
@endforeach

Upvotes: 1

Views: 503

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81147

To access ->pivot->whatever you need to add withPivot('whatever') to the relation definition:

public function relations()
{
  return $this->belongsToMany('Relation')->withPivot('relationship');
}

Note: I wouldn't use relations and Relation names here, since it's misleading AND it may collide with Eloquent\Model stuff.

Upvotes: 2

Related Questions