I have Eloquent with a HasMany relationship. I need to filter only hasmany relationship if the first record is the current month.
Model
public function attendanceclasses(){
return $this->hasMany('App\Studentattendance','assign_id','id')->WhereIn('attendance_status',[2,3,6]);
}
public function firstattendadclass(){
return $this->hasOne('App\Studentattendance','assign_id','id')->WhereIn('attendance_status',[2,3,6])->OrderBy('class_date','ASC');
}
Query
$q->Where('class_date', '>=',date('Y-06-01'));
$q->Where('class_date','<=',date('Y-m-t'));
})->get();
You have to filter in `with'. This will filter both parent and child
$firstOfMonth= Carbon::now()->firstOfMonth()->toDateString();
$lastOfMonth=Carbon::now()->lastOfMonth()->toDateString();
$stucourselist=StudentCourses::with(['firstattendadclass'=>function($q)use($firstOfMonth,$lastOfMonth){
$q->Where('class_date', '>=',$firstOfMonth);
$q->Where('class_date','<=',$lastOfMonth);
}])->whereHas('firstattendadclass',function($q)use($firstOfMonth,$lastOfMonth){
$q->Where('class_date', '>=',$firstOfMonth);
$q->Where('class_date','<=',$lastOfMonth);
})->get();
if you want to filter only child then you can remove wherehas
Also you can use whereBetween('class_date',[$firstOfMonth,$lastOfMonth])