user3216673 user3216673 - 5 months ago 20
PHP Question

Laravel 5 – get particular many to many relation based on model and related model ID

I've got

Tag
and
Attendee
Eloquent models, they are in many-to-many relation. Pivot table has also two more attributes –
value_int
and
value_string
. My
Attendee
model looks like this:

class Attendee extends Model
{
public $timestamps = false;

protected $fillable = [
'event_id'
];

public function tags() {
return $this->belongsToMany('App\Models\Tag', 'attendee_tag', 'attendee_id', 'tag_id')
->withPivot(['value_string', 'value_int']);
}

public function scoreTagValue($tag_id) {
return $this->tags->where('tag_id', '=', $tag_id)->first();
}

}


What I want is to obtain pivot values based on
Attendee
model and variable
tag_id
, so I've written
scoreTagValue
function, but it always returns
null
and I don't know why :( I'm calling it this way:
$attendee->scoreTagValue($tag_id)
. Thanks for your help :)

Answer Source

You need to access the relation, not the property:

public function scoreTagValue($tag_id) {
    return $this->tags()->where('tag_id', '=', $tag_id)->first();
}

Also, according to the docs, withPivot() does not take an array, so:

->withPivot('value_string', 'value_int');