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

Charrua's avatar

Laravel relation query taking too much time to load

Hello, I have two models, one for school Member and the other for school Attendance, each one with the corresponding database table.

My goal is to get all school members who have at least one attendance between some particular date, as an example let's take '2019-04-05' and '2019-04-12' (one week)

So in my Members model I have a relation:

public function attendance() {
    return $this->hasMany('App\Attendance')
        ->whereBetween('scan_date', array('2019-04-05', '2019-04-12'));
}

The problem is that the attendance table has like 76000 records now so the query takes about 8 seconds to get the results. Is there a way to make this query faster? maybe limit in some way?

0 likes
9 replies
munazzil's avatar

Check with below query use the limit(),

   ->whereBetween('scan_date', array('2019-04-05', '2019-04-12')->limit(100)->get());
Charrua's avatar

@STAUDENMEIR

$members = \App\Member::withoutGlobalScope(SchoolScope::class)
        ->whereNotNull('email')
        ->when($to_school, function ($query, $to_school) {
            return $query->where('school_id', $this->communication->school_id);
        })
        ->has('attendance')
        ->get();
select * from `members` where `email` is not null and `school_id` = ? and exists (select * from `attendances` where `members`.`id` = `attendances`.`member_id` and `scan_date` between ? and ? and `attendances`.`deleted_at` is null) and `members`.`deleted_at` is null

The relation query is the one that is taking long time ->has('attendance') without that, it works replay quickly

Charrua's avatar

@MUNAZZIL - This does the same, 8 seconds waiting... I even try to limit to 10 but no luck.

munazzil's avatar

->has('attendance') replace and use below one,

->with('attendance')

else

 return $query->where('school_id', $this->communication->school_id)->with('attendance');
staudenmeir's avatar
Level 24

Have you analyzed the query with EXPLAIN? Does the scan_date column have an index?

2 likes
Charrua's avatar

@STAUDENMEIR - Seems that adding an index the query time is as expected, I'll post results here. Thank you

lostdreamer_nl's avatar

staudenmeir is right, check your indexes on your database: Make sure that at least these fields have an index applied to them:

  • member_id
  • scan_date
  • deleted_at (optional)

That should speed up your query a lot. if you don't have an index on scan_date, it's doing a complete table scan....

1 like

Please or to participate in this conversation.