Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
Hasmany Relationship where first record is current month in laravel

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();
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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])

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!