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

TheBlueDragon's avatar

How i can filter through model collection?

hello, i have a question regarding the filtering

i have a condition i need to apply like this

$students_list = Student::all();
$students_list[0]->examResult()->whereexamstype_id(6)->whereexam_result('Pass');

which return for me the student if he pass (will display his information, if not then will give an empty result)

and i was trying to make a better way of filtering so i got only the pass students to my view without make extra methodes or extra lines

so i make the code like this

$students_list = Student::all();
    $students = $students_list->filter(function($student)
    {
        return $student->examResult()->whereexamstype_id(6)->whereexam_result('Pass');
    });

but its give me the list of all students without filtering them so can someone tell me where is my mistake so i can fix it or i understand the filter mistake !!

thanks

0 likes
3 replies
willvincent's avatar
Level 54

Why not just change your query to use whereHas instead of all?

$exam_id = 6;
$passing_students = Student::whereHas('exam', function ($q) use ($exam_id) {
  $q->where('type_id', '=', $exam_id)
  $q->where('result', '=', 'Pass')
})->get();

I'm making some assumptions here about your relationships and data structure.. but this would probably be a better approach.

1 like
willvincent's avatar

I've never used filter.. I guess filtering might make sense if you needed to split a list of results into multiple lists by different criteria, but fetching only those results you want in the initial query will always be the more performant solution.

1 like

Please or to participate in this conversation.