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

mkdesign82's avatar

WhereHas Does Not Return All records On Empty search

Hello , I'm trying to fetch all of the students in the table if they have any course related to their id , other wise if there is no course id to select from return all the students . I have wrote this part

$students = $this->student->whereHas("course", function($query){
                $query->where("l_courses.id", "LIKE", "%".$this->course_id."%");
            })->get();

but this part of code retrieve just those students which has course if there were not any course id . any Clue ?

0 likes
3 replies
tomopongrac's avatar

Try this

$course_id = $this->course_id;
$students = $this->student->whereHas("course", function($query) use ($course_id) {
                $query->where("l_courses.id", "LIKE", "%". $course_id ."%");
            })->get();
willvincent's avatar

Why would the where condition use LIKE to match the id? That should be $query->where('l_courses.id', '=', $course_id); shouldn't it? A sort of 'fuzzy match' on ids between tables seems odd, and wrong.

But yes, @tomi is right, you need to include the use() to populate $course_id into the closure.

1 like
mkdesign82's avatar

@willvincent Well is not about the operator sign , is about returning all records if the search keyword was empty. By the way you can reference the object propertise from the inside of the closure . and Ofcourse we should use (use) to import variable into the closure , but my question was not related to how using course_id in the closure.

Please or to participate in this conversation.