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

babai9's avatar

How to show only those values which have status=0 in eloquent query in laravel?

I have to work on two of my main models Assessment and User where I have a hasOne relation, in which assessments table have created_by as foreign key from users table. I need to fetch only those assessments whose status are 0 also of the users whose status are 0. The issue I am facing with my query is it is returning all of the assessments, if the users status is not 0 then also it is showing their assessments, if user status is 1 then dont' show those assessments, if is 0 show them. Help me to find the issue with this query

$data = Assesment::with(['age:id,age','curriculumUnit:id,unit_name','subject:id,subject_name','assesmentQuestions','user' =>  function($q){ $q->select('id')->where('status',0); }])->select(['id','assesment_name','subject_id','curriculum_id','focus_area','age_id','description','created_at','status','created_by'])->where('status',0)->orderBy('id','DESC')->paginate($this->pagination_assesments_records);

0 likes
2 replies
tangtang's avatar
tangtang
Best Answer
Level 6

@babai9

you should use the whereHas method to filter assessments based on the related user's status

here the reference

$data = Assesment::with(['age:id,age','curriculumUnit:id,unit_name','subject:id,subject_name','assesmentQuestions','user' => function($q) {
    $q->select('id')->where('status', 0);
}])
->whereHas('user', function($q) {
    $q->where('status', 0);
})
->select(['id','assesment_name','subject_id','curriculum_id','focus_area','age_id','description','created_at','status','created_by'])
->where('status', 0)
->orderBy('id','DESC')
->paginate($this->pagination_assesments_records);

babai9's avatar

@tangtang Thanks! I really forgot whereHas I have used in other some functions

Please or to participate in this conversation.