'Many-to-many relation Laravel Eloquent. Fetch related table with specific related id

I am writing a query in Laravel 8 using Eloquent. There is a many-to-many relation between subjects and streams and their pivot table is courses.

subjects: id name

streams id name

courses id subject_id stream_id

I have to fetch subjects with specific stream.

I have written the following query.

$this->subjects = Subject::has('streams',$this->stream)->get();

I am having problem in this.

courses table :

id stream_id subject_id
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
6 2 2
7 3 1

This is the sample data. If I want to fetch subject where stream id is 1 then it is only fetching subject with ids 3 and 4 and not fetching subjects with id 1 and 2. Can anyone explain me why it is skipping subject ids with 1 and 2 ?

PLease anyone can help me with this. Thank you in advance . :)

Edited

class Subject
{
   public function streams()
    {
        return $this->belongsToMany(Stream::class, 'courses', 
'subject_id', 'stream_id');
    }
}


class Stream
{
   public function subjects()
    {
        return $this->belongsToMany(Subject::class, 'courses', 
'stream_id', 'subject_id');
    }
}


Solution 1:[1]

For fetching models having a specific related model you can use whereHas() method. https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

Assuming that $this->stream is a Stream model, you can use a closure for whereHas method:

$stream = $this->stream;

$this->subjects = Subject::whereHas('streams', function($query) use ($stream){
   $query->where('streams.id', $stream->id);
})->get();

Edit: since $this->stream is an id you should do

$stream = $this->stream;

$this->subjects = Subject::whereHas('streams', function($query) use ($stream){
   $query->where('streams.id', $stream);
})->get();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1