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

Deekshith's avatar

Filter null value in nested relationship

i have tables like below,

course_center_mapping

id, course_id,center_id,mode_availability
1, 1, 1, Both
1, 1, 2, Offline
1, 1, 3, Online

Course.php (Model)

public function centermapping()
    {
      return $this->hasMany('App\CourseCenterMap','course_id','course_id');
    }

CourseCenterMap.php

public function centerdetail()
    {
      return $this->belongsTo('App\Centers','center_id','id');
    }

In controller i have a code like below,

$modes = ['Both','Offline'];
$coursedetails = Courses::with(['centermapping'=> function($q) use($modes) {
            $q->where('status','Active')
                ->whereIn('mode_availability',$modes);

        },'centermapping.centerdetail' => function($q) {
            $q->where('active',1);
        }])->where('menu_name',$courseslug)->where('course_active',1)->first();

and above query is working fine but i want to filter out centermapping if centerdetail is null.

0 likes
3 replies
vincent15000's avatar

You can try to add Courses::whereHas('centermapping.centerdail') to your query.

Tell me if it helps ;).

1 like
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

I assume you mean a relation must exist? Or is it a column on centerdetail that cannot be null?

$coursedetails = Courses::with(['centermapping'=> function($q) use($modes) {
            $q->where('status','Active')
                ->whereIn('mode_availability',$modes)
                 ->has('centerdetail');

        },'centermapping.centerdetail' => function($q) {
            $q->where('active',1);
        }])->where('menu_name',$courseslug)->where('course_active',1)->first();
Deekshith's avatar

@Sinnbeck Great. Thank you it worked. Yes i wanted to check if centerdetail relationship exists with centermapping. adding ->has('centerdetail'); solved the problem.

Thank you so much.

Please or to participate in this conversation.