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

Dhruva's avatar
Level 11

How to use Scope for Intermediatble Table in Many to Many Relationships

Hi All

I am trying to use scope for retrieving column field name from many to many relationship's intermediate table.

Pivot Table fields are

  • quiz_id
  • batch_id
  • start_date
  • end_date
  • points

Model - Quizzes

 public function selectedBatch($batchId)
    {
        return $this->belongsToMany(\App\Batch::class , 'quizzes_batches',  'quiz_id', 'batch_id')
        ->using('App\QuizBatch')
        ->withPivot(
            'start_date', 'end_date', 'points')
        ->wherePivot('batch_id', $batchId)->firstOrFail();
    }

And the scope method is

    public function scopePoints($query)
    {
        return $query->pivot->points;
    }

I want to get points value (the column is in pivot table) from a particular batch (among all batches belongs to quiz).

Now when I try to retrieve following code, I am not getting any result

$quiz->selectedBatch($batchId)->marks();

Please guide me, where I am doing wrong.

0 likes
3 replies
bobbybouwmann's avatar

I'm not sure what you mean here, because your selectedBatch method doesn't use the points scope here.

If you mean to use the scope in the withPivot method then I can already tell that this won't work.

1 like
Dhruva's avatar
Level 11

Hi.. It was mistake.

the last code was

$quiz->selectedBatch($batchId)->points();

bobbybouwmann's avatar

Well, the scope only works on the query builder object. However your selectedBatch method returns a Batch model. So you should remove the firstOrFail so you can keep chaining on the query.

1 like

Please or to participate in this conversation.