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

vincent15000's avatar

Query builder with with() to retrieve relationships

Hello,

I try for hours to understand why the $trainingId is not filtering the courses.

public function listByTraining($trainingId)
{
	$trainingId = 8; // I even added this here to verify
    $courses = Course::
        with(['teachingUnitSubject' => function($query) use($trainingId) {
            $query
                ->with(['teachingUnit' => function($query) use($trainingId) {
                    $query->with(['training' => function($query) use($trainingId) {
                        $query
                            ->where('id', $trainingId)
                            ->where('society_id', auth()->user()->society_id);
                    }]);
                }])
                ->with('subject');
        }])
        ->orderBy('start_date')->get();
    return $courses;
}

I always retrieve all the courses without filtering by trainingId.

What's wrong with my code ?

Would it be perhaps better to add a training_id field to the teaching_unit_subjects table ?

Thanks for your help ;).

V

0 likes
6 replies
MichalOravec's avatar
Level 75
public function listByTraining($trainingId)
{
    return Course::with(['teachingUnitSubject.teachingUnit.training' => $closure = function ($query) use ($trainingId) {
        $query->where('id', $trainingId)->where('society_id', auth()->user()->society_id);
    }, 'teachingUnitSubject.subject'])
        ->whereHas('teachingUnitSubject.teachingUnit.training', $closure)
        ->orderBy('start_date')
        ->get();
}
1 like
vincent15000's avatar

Hello @michaloravec I didn't know that it was possible to chain the relationships in the with() method. I will try this and tell you if it works ;).

vincent15000's avatar

Waouhhh ... It works perfectly now ;) !!!

Now I nearly have no doubt about the fact you're probably the big boss ;).

I always forget the whereHas() method ...

Thanks a lot @michaloravec.

Please or to participate in this conversation.