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

33sKamal's avatar

Get data from multiple joined tables with a null foreign key

suppose we have 6 students 2 got level and 4 non -> students ( id, level_id, group_id, ..) -> group( id, ..) -> level(id,..)

on students the " level_id " may be null : students may not got a level

how can i get all the students using join or with ( with ability of searching ) i use join it returns only 2 tried leftJoin nothing ... Help & Thanks

0 likes
4 replies
Snapey's avatar

why not $students=Student::with('level')->all();

33sKamal's avatar

Yes this returns all the students event null levels but if i typed level one on search i need just the levels titled

36864's avatar
->whereHas('level', function($query) use ($search_levels){
    if ($search_levels !== null) {
        $query->whereIn('level_id', $search_levels);
    }
}
33sKamal's avatar

this returns students whether he got level or not ( with level null if it is null )

i want not to return the user if it's level = null

Please or to participate in this conversation.