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

mansoorkhan's avatar

Eloquent condition inside nested with()

Hi, I need some help! On line number 3, I want to pass student.level_id (dynamic value from within the query results) in where('level_id', ??) dynamically. Any idea How should I do it?

In other words, I want to convert this SQL query to Eloquent:

SELECT * FROM levels
JOIN students on (levels.id = students.level_id)
JOIN examinations on (examinations.level_id = students.level_id AND examination.student_id = students.id)

This is the code I have tried so far.

$levels = Level::with(['students' => function ($query) {
            $query->with(['examination' => function ($inner_query) use ($query) {
                $inner_query->where('level_id', '???');
            }]);
        }])->get();
0 likes
5 replies
sr57's avatar

I don't answer directly to your question but personally I never use Eloquent for 'complex' query, u can :

DB::select("your SQL");

It's faster to write and runs faster.

1 like
mansoorkhan's avatar
mansoorkhan
OP
Best Answer
Level 3

I use this amazing package, https://github.com/topclaudy/compoships And this is the solution I have come up with.

// App\Models\Level
public function studentsExaminationResult()
{
    return $this->hasMany(Student::class, 'level_id');
}

// App\Models\Student;
use \Awobaz\Compoships\Compoships; // Package Trait to be able to use multi foreign key relations
public function examination()
{
    return $this->hasMany(
        Examination::class,
        ['student_id', 'level_id'],
        ['id', 'level_id']
    )
    ->orderBy('subject_id');
}

// App\Http\Controllers\ExaminationController;
$examinationResult = Level::with([
    'subjects',
    'studentsExaminationResult' => fn ($query) => $query->with([
    'examination' => fn ($inner_query) => $inner_query->where('year', $year)
           ->where('term', $term),
    ]),
])->get();

Please or to participate in this conversation.