You have to use whereHas instead of with if you want to filter your courses.
https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Right now you are simply restricting the results of the training relationship.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
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();
}
Please or to participate in this conversation.