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

Deekshith's avatar

laravel wherehas is slow for more than 100k records

Hello All, I have a tables like below,

users

id, name, email

courses

id, course_name, description

and user_courses

id, user_id, course_id

now i am trying to fetch user with assigned courses so in user model i have added code like below,

public function assignedcourses()
    {
      return $this->belongsToMany('App\Course','user_courses','user_id','course_id');
    }

now i am trying to fetch data like below,

$coursemanagers = User::whereHas('assignedcourses')->with('assignedcourses')->get();

But above code is taking more time like more than 3 minutes to display the data. how to optimise above query?

Thank you

0 likes
3 replies
JakeCausier's avatar

You could drop the whereHas function from your query, since with will load the courses if they exist for the users that have some and simply return null for the user that don't.

Sinnbeck's avatar

Make sure you have properly set indexes. Use EXPLAIN in front of the query in a database manager to see the indexes used

Please or to participate in this conversation.