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

hosamalzagh's avatar

how use whereHas with belongsToMany relation

i have this table name exam_starts

https://i.ibb.co/f4Pwrwc/asd.jpg

i need to get unique student_id and exam_id = 3 and status must =1 in all row

ex ids from 562 to 556 this is one result

i need search ex select all student from table name where exam_id = 3 status =1 from 562 to 556

i try


 \App\exam->students()
            ->whereHas('exams' , function ($q){
                return $q->where('exam_id', 3)->where('exam_starts.Status','!=',[3]);
             })->get()

Model


class Exam extends Model
{
`    public function students(){
        return $this->belongsToMany('App\Student','exam_starts','exam_id','student_id')
            ->withPivot(['exam_class_id','Attend','pass','Status','exam_code_id'])->withTimestamps();
 }
    }

0 likes
2 replies
tisuchi's avatar

@hosamalzagh I may think in a bit different way.

In your model, add a new method -


class Exam extends Model
{
    public function students(){
        return $this->belongsToMany('App\Student','exam_starts','exam_id','student_id')
            ->withPivot(['exam_class_id','Attend','pass','Status','exam_code_id'])->withTimestamps();
 	}

 	public function getUniqueStudents(){
 		return $this->students->where([
 			'exam_id' => 3,
 			'status' => 1
 		])
 		->groupBy('student_id')
 		->get();
 	}
}

BTW, you need to use groupBy('student_id') as you described in your question.

Then call it in the controller-

\App\exam->getUniqueStudents();
hosamalzagh's avatar

LogicException App\Exam::getUniqueStudents must return a relationship instance

    public function getUniqueStudents(){
            return $this->students()->where([
                    'exam_id' => 3,
                    'exam_starts.status' => 1
             ])->groupBy('student_id')
           ->get();
    }

i add () to students

Please or to participate in this conversation.