Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MattB's avatar
Level 2

How to get extra info from pivot table

I have 3 tables: emotions, users, and emotion_user. The emotion_user table has an extra column in it called emotion_score. I can query the emotion table through users and get a list of emotion names, but how would I get the emotion_score out of the pivot table in the controller?

To get the emotion names I can use this:

$emotionScore = User::find(Auth::user()->id)->emotion()->get()->pluck('name');

But I need the scores. The two models are: User:

public function emotion()
    {
        return $this->belongsToMany(Emotion::class)->withPivot('emotion_score');
    }

Emotion:

public function user()
    {
        return $this->belongsToMany(User::class)->withPivot('emotion_score');
    }

Further to this, I wanted to get a sum of all the scores for a particular user so I was trying something like this:

$score = 0;
        foreach($request->emotions as $emotion) {
            $emotionScore = User::find(Auth::user()->id)->emotion()->get();         
            $score += $emotionScore;
        } 

but I was stuck on getting the emotion scores

0 likes
2 replies
MattB's avatar
Level 2

Sorry I should have included the output:

array:4 [▼
  1 => "on"
  2 => "on"
  3 => "on"
  4 => "on"
]

I tried with

foreach($request->emotions as $key=>$id) {          
            $emotionScore = User::find(Auth::user()->id)->emotion()->get();   
            $score += $emotionScore;
        }  

but I got myself in a right mess.

automica's avatar

@mattb your relationship should be plural:

public function emotions()
    {
        return $this->belongsToMany(Emotion::class)->withPivot('emotion_score');
    }

then you can get

$score = 0;

$emotions = User::find(Auth::user()->id)->emotions()->get();

foreach($emotions as $emotion) {
            $emotionScore = $emotion->pivot->emotion_score;      
            $score += $emotionScore;
        }

Please or to participate in this conversation.