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

MattB's avatar
Level 2

Pivot table queries, many to many help

I need help getting my head around a pivot table query. I have 3 tables; emotions, scores, and UserEmotionScores. I am struggling to query through the pivot table as I keep getting error:

Trying to get property 'name' of non-object

Here is my controller:

public function show($index)
    {      
        $emotionScores = UserEmotionScore::where('user_id', Auth::user()->id)->get();      
        return view('home.track', compact('emotionScores'));
    }

Blade:

 @foreach ($emotionScores as $score)            
        <div class="col-4 col-md-3 text-center" id="{{ $score->emotion->name }}"><p class="emotionCircleSelected">{{ $score->score }}</p></div>
    @endforeach

emotion model:

public function useremotionscore()
    {
        return $this->belongsTo(Emotion::class, "emotion_id");
    }

UserEmotionScore model:

public function emotion()
    {
        return $this->hasOne(Emotion::class, "id");
    }

I realise I didn't follow the naming convention for the pivot table, does that break it? How would I get this to work please? The scores in the pivot table are being filled in through choices made by the user in an earlier step in the website, through choices made with radio buttons, so there is no scores table.

0 likes
1 reply
bugsysha's avatar

Naming is super confusing... Where is the third model?

Please or to participate in this conversation.