The issue you're encountering is likely due to the way the where clause is being applied in the hasManyThrough relationship. When you define a relationship in Laravel, the where clause is applied at the time of relationship definition, which might not have access to the dynamic context (like $this->course_id) you expect.
To solve this, you can use a closure to define the relationship and apply the where clause dynamically when querying. Here's how you can adjust your userEducations method:
public function userEducations()
{
return $this->hasManyThrough(
UserEducation::class,
User::class,
'id', // Foreign key on the User table...
'user_id', // Foreign key on the UserEducation table...
'user_id', // Local key on the Applicant table...
'id' // Local key on the User table...
);
}
// When querying, apply the where clause dynamically
public function getUserEducations()
{
return $this->userEducations()->where('user_education.course_id', $this->course_id)->get();
}
Then, when you want to load the relationship with the condition, you can use the getUserEducations method:
$applicant->load(['user', 'course.program', 'country', 'city', 'languages', 'leadership']);
$educations = $applicant->getUserEducations();
This approach separates the relationship definition from the query logic, allowing you to apply dynamic conditions when you actually perform the query.